0

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.

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?

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)
...
2
  • 3
    You can accomplish what you want with setattr, but are you sure you want to? Why not create a dict or list instead? Commented Dec 17, 2013 at 7:58
  • 6
    keep your data out of your variable names. Commented Dec 17, 2013 at 8:00

2 Answers 2

8

You can do this with setattr, but I don't recommend it:

for i in range(1,5):
    setattr(self, 'folderheader%s' % i, QtGui.QLabel(self.folders))

Instead, might I suggest a 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...

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. The setattr works beautifully. However, I tried out your list method, and it worked much better and is much cleaner! Thank you very much.
1

You can use a dict like this

self.foldersdict = {}
for i in range(100):
    self.foldersdict[i] = QtGui.QLabel(self.folders)

You can later access them like this,

self.foldersdict[1]

1 Comment

Dictionary with integer key? Sound like recipe for list. self.foldersdict = [ QtGui.QLabel(self.folders) for _ in xrange(100)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.