[英]Recursively declaring variables - python
Normally I would never want to do this, but in this case I feel as though there's no alternative. 通常,我永远都不想这样做,但是在这种情况下,我觉得别无选择。 I'm building a program in pyqt that has many label widgets, and alot of which are the same with the exception of a couple places on the geometry. 我正在pyqt中构建一个程序,该程序具有许多标签小部件,除了几何上的几个地方外,其他很多小部件都相同。
I would like to automate declaring them instead of having to declare them line by line which is taking up a lot of lines. 我想自动化地声明它们,而不必一行一行地声明它们,这占用了很多行。 It also looks pretty ugly. 它看起来也很丑。
Is there a way to say create ten variables like var1, var2, var3, etc. without having to declare them line by line? 有没有办法说创建十个变量,例如var1,var2,var3等,而不必一行一行地声明它们?
Right now my code looks like- 现在我的代码看起来像-
self.folderheader1 = QtGui.QLabel(self.folders)
self.folderheader2 = QtGui.QLabel(self.folders)
self.folderheader3 = QtGui.QLabel(self.folders)
self.folderheader4 = QtGui.QLabel(self.folders)
...
You can do this with setattr
, but I don't recommend it : 您可以使用setattr
做到这一点,但我不建议这样做 :
for i in range(1,5):
setattr(self, 'folderheader%s' % i, QtGui.QLabel(self.folders))
Instead, might I suggest a list
? 相反,我可以建议一个list
吗?
self.folderheaders = [QtGui.Qlabel(self.folders) for _ in range(1, 5)]
Now instead of self.folderheaders1
you have self.folderheaders[0]
which isn't really that different... 现在,而不是self.folderheaders1
你有self.folderheaders[0]
这是不是真的那么不同?
You can use a dict
like this 您可以使用这样的dict
self.foldersdict = {}
for i in range(100):
self.foldersdict[i] = QtGui.QLabel(self.folders)
You can later access them like this, 您以后可以像这样访问它们,
self.foldersdict[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.