Reputation: 9
I'm quite new to Python, but come from a Lua background. I know exactly how I would achieve this in lua. I'm sure the answer already exists but I don't know how to ask the question - what terminology to search for? Things like 'dynamically define variables' return a lot of arguments, along with advice to use dictionaries as that is what they are for. But in my case dictionaries don't seem to work.
A condensed example, where Button(ID) is creating an instance of a button class:
Button1 = Button(8)
Button2 = Button(3)
Button3 = Button(432)
ButtonClose = Button(5004)
As there are more than 4 buttons in my actual UI, and I do more with them than just instantiate the class objects, I wish to use a loop structure of some sort to condense the code.
BtnList = {'Button1' : 8, 'Button2' : 3, 'Button3' : 432, 'ButtonClose' : 5004,}
for btn,ID in BtnList:
# some code here
I've tried using the following outside of any loops/functions, to avoid scoping issues while testing:
btns = {}
btns.Button1 = Button(8)
But this doesn't seem to be possible as I get an error:
AttributeError: 'dict' object has no attribute 'Button1'
Help please?
Upvotes: 0
Views: 91
Reputation: 1792
You have a problem with dict mapping. It should be changed to
btns = {}
btns["Button1"] = Button(8)
Then the string "Button1" inside the btns dictionary will contain the Button Object.
Upvotes: 1