python - 我可以使用具有类属性/函数的变量吗?
问题描述
它不允许我使用具有类属性的变量。不知道如何管理这个。我需要得到 7 的答案。但我需要能够使用该变量。给我错误,
回溯(最后一次调用):文件“c:/Data/First Game (Python)/rough.py”,第 32 行,在 a.add_2(5) AttributeError: 'str' object has no attribute 'x'
我认为它无法通过我的意思提到 Me1 来识别这一点。
class Test():
def add_2(self, y):
print(y + 2)
Me1 = Test()
for i in range (1):
a = "Me" + str(i+1)
print (a)
a.add_2(5)
解决方案
除非您正在探索要学习的东西,否则在运行时构造类的对象没有任何意义。但是,这就是你要找的,
class Test():
def add_2(self, y):
print(y + 2)
Me1 = Test()
for i in range (1):
a = "Me" + str(i+1)
print(a)
b = eval(a) # converting str to Class Test object
b.add_2(5)
输出:
Me1
7
推荐阅读
- haskell - 在haskell语言的谓词中绑定let的问题?
- c++ - 概念中的嵌套类型绑定在 GCC 和 clang 上失败,但在 msvc 上失败
- php - Phpspreadsheet excel解析抛出500内部服务器错误
- mongodb - Spring Boot API 响应的变化
- bash - 在 bash 脚本中将 CSV 文件不均匀地拆分为多个文件
- c# - 销毁命令不适用于粒子系统
- angular - 所有项目的 MAT_RADIO_DEFAULT_OPTIONS
- node.js - Discord JS Cooldown 与验证
- load-balancing - 将请求转发到正确的分片
- arrays - Neo4j foreach 子句循环遍历字符串数组的元素