包含变量的Python属性名
我正在用Qt+Python编写一个桌面程序,目前我在调用一些名称中带有变量的属性时遇到了一个问题包含变量的Python属性名,python,python-3.x,qt,pyqt,Python,Python 3.x,Qt,Pyqt,我正在用Qt+Python编写一个桌面程序,目前我在调用一些名称中带有变量的属性时遇到了一个问题 self.checkBox_Answer1.clear() self.checkBox_Answer2.clear() self.checkBox_Answer3.clear() self.checkBox_Answer4.clear() 数字是变量,所以我想要 self."checkBox_Answer%d" % (A).clear() if A == 1: self.checkBox
self.checkBox_Answer1.clear()
self.checkBox_Answer2.clear()
self.checkBox_Answer3.clear()
self.checkBox_Answer4.clear()
数字是变量,所以我想要
self."checkBox_Answer%d" % (A).clear()
if A == 1:
self.checkBox_Answer1.clear()
if A == 2:
self.checkBox_Answer2.clear()
if A == 3:
self.checkBox_Answer3.clear()
if A == 4:
self.checkBox_Answer4.clear()
其中“A”是我计算的变量,但这种编码方式不起作用
也试过
self.str("checkBox_Answer"+"%d" % (A)).clear()
self.checkBox_Answer+"%d" % (A).clear()
什么都不管用
我知道我可以做像这样的事情
self."checkBox_Answer%d" % (A).clear()
if A == 1:
self.checkBox_Answer1.clear()
if A == 2:
self.checkBox_Answer2.clear()
if A == 3:
self.checkBox_Answer3.clear()
if A == 4:
self.checkBox_Answer4.clear()
但是,难道没有更多的python方法来做这件事吗?我会将这些变量存储在一个列表中:
self.checkboxAnswers = [checkBox_Answer1,etc...]
self.checkboxAnswers[A].clear()
您可以使用A访问列表中的这些变量。请注意,列表从索引0开始,因此您必须将A增加1。您可以使用反射获取属性名称。这会影响你的表现,但这是一种比地图更干净的方式 它看起来像:
getattr(self, "checkBox_Answer"+"%d" % (A))
是的,将复选框答案粘贴到字典中,其中的键是
Answer1
,Answer2
,等等。您是否尝试过使用.format()之类的东西,如谢谢!当我希望它工作时,我工作了getattr(self,“checkBox_-Answer”+“%d”%(A)).setText(buf[buf.find(“)”)+1:])