Python: Dynamic attribute name generation without exec() or eval()

Posted by PyNewbie27 on Stack Overflow See other posts from Stack Overflow or by PyNewbie27
Published on 2010-03-23T02:23:39Z Indexed on 2010/03/23 2:31 UTC
Read the original article Hit count: 289

Filed under:
|

Hi,

I'm trying to dynamically create buttons at runtime with PyQT4.7

However, this being my first python program I'm not sure how to get the functionality I want.

I would like to be able to substitute a text string for an attribute name:

i.e.

for each in xrange(4):
    myname = "tab1_button%s" % each  #tab1_button0, tab1_button1, tab1_button2

    #self.ui.tab1_button0 = QtGui.QPushButton(self.ui.tab) <--normal code to create a named button
     setattr(self.ui,myname,QtGui.QPushButton(self.ui.tab)) #rewrite of line above to dynamicly generate a button

#here's where I get stuck. this code isn't valid, but it shows what i want to do
     self.ui.gridLayout.addWidget(self.ui.%s) % myname
#I need to have %s be tab1_button1, tab1_button2, etc. I know the % is for string substituion but how can I substitute the dynamically generated attribute name into that statement?

I assume there's a basica language construct I'm missing that allows this. Since it's my first program, please take it easy on me ;)

© Stack Overflow or respective owner

Related posts about python

Related posts about pyqt4