Python 3 getattr 字符串到名称为何不好?
我有一个字符串:`("Bit" + str(loopCount))`。
这里的loopCount只是一个我在循环中不断增加的数字。
我想用这个字符串创建一些qtwidget,像这样:
self.Bit1 = QtGui.QLineEdit(self)
self.Bit2 = QtGui.QLineEdit(self)
self.Bit3 = QtGui.QLineEdit(self)
...以此类推,直到我在LoopCount中有的数量。
为了做到这一点,我需要把我的字符串转换成一个名字。网上查了一下,发现了这个叫getattr的东西,感觉是最简单的方法:
for BitNmb in range(0, self.mySpnValue):
getattr(self, ("Bit" + str(loopCount)))
但是我遇到了这个错误:
AttributeError: 'Class2' object has no attribute 'Bit1'
这让我很沮丧,因为我在错误信息中看到了我想要的“Bit1”,但我不知道为什么它要成为我类的一个属性。
而且没有简单的方法可以做到这一点。
getattr(self, ("Bit" + str(loopCount) )) = QtGui.QLineEdit(self)
error : SyntaxError: can't assign to function call
我看过很多次“不要把getattr当成字典来用”,好吧……但为什么呢?用字典听起来为了做这么简单的事情要花很多功夫?
谢谢
1 个回答
2
与其创建单独的、带编号的属性,不如使用列表或字典。在这种情况下,使用列表就很好:
self.bits = [QtGui.QLineEdit(self) for _ in range(3)]
这段代码创建了3个 QLineEdit
对象的列表。
要动态地 设置 属性,可以使用 setattr()
函数:
setattr(self, 'Bit{}'.format(loopCount), QtGui.QLineEdit(self))