【发布时间】:2022-01-03 18:14:43
【问题描述】:
我想使用变量来访问由类创建的对象的属性,但是 Python 使用变量的名称作为对象的名称,而不是存储在变量中的名称。
class button():
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
white = (255,255,255).
A1 = button(white, 50, 50, 20, 20, text='Hello World')
var = "A1"
print(var.text)
当我运行它时:
AttributeError: 'str' object has no attribute 'text'
有没有办法在调用var.text时使用var里面的信息作为对象名?
【问题讨论】:
-
这能回答你的问题吗? How do I create variable variables?
-
变量名是为了编码者的利益,而不是代码本身。如果你的代码需要一个变量名,这意味着你应该使用
dict。 -
应该避免 - 但
print(eval(var).text)也可以。 -
任何时候你想
Variable variables想dict(或其他语言,关联数组)。任何其他通过变通方法或可怕的php之类的废话来实现这一点的方法都会造成混乱,并且可能会在下一个开发人员看到您的代码时导致您的生活。
标签: python class attributeerror