[英]Can I use a variable with a class attribute / function?
It doesn't allow me to use a variable with an attribute of the class.它不允许我使用具有 class 属性的变量。 Not sure how to manage this.
不知道如何管理这个。 I need the answer to come out as 7. But I need to be able to use the variable for it.
我需要得到 7 的答案。但我需要能够使用该变量。 gives me the error,
给我错误,
Traceback (most recent call last): File "c:/Data/First Game (Python)/rough.py", line 32, in a.add_2(5) AttributeError: 'str' object has no attribute 'x'回溯(最后一次调用):文件“c:/Data/First Game (Python)/rough.py”,第 32 行,在 a.add_2(5) 中 AttributeError: 'str' object 没有属性 'x'
I think it is not able to recognize that by a I meant to mention Me1.我认为它无法通过我的意思提到 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)
From what I see the variable a
is a string while the function a.add_2(5)
belongs to the objects of class Test
.从我看到的变量
a
是一个字符串,而 function a.add_2(5)
属于 class Test
的对象。 The error is caused by the fact that you call a method of class Test
on a string该错误是由于您在字符串上调用 class
Test
方法引起的
It doesn't make any sense on constructing an object of a class at runtime unless you're exploring something to learn.除非您正在探索要学习的东西,否则在运行时构造 class 的 object 没有任何意义。 But, here is what you're looking for,
但是,这就是你要找的,
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)
Output: Output:
Me1
7
Reference: https://docs.python.org/3/library/functions.html#eval参考: https://docs.python.org/3/library/functions.html#eval
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.