[Tutor] Dynamically named objects

Chris Fuller cfuller084 at thinkingplanet.net
Fri Dec 28 09:40:20 CET 2007


You might find a dictionary useful. Each element in a dictionary is associated 
with a "key", which can be a string.

objectlist = {}
o = eval("class1" + "()")
objectlist["object1"] = o
o.method("hello world")

Also, try to avoid using eval(), it usually makes troubleshooting and 
maintenance harder and can lead to security problems in some cases. You could 
have a dictionary of classes and look them up on the fly:

classlist = { "classone" : classone, "classtwo" : classtwo }

objectlist = {}
cls = classlist[user_input]
o = cls()
objectlist["object1"] = o
o.method("hello world")

Cheers


More information about the Tutor mailing list