generating objects of a type from a name.

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 27 09:50:13 CEST 2007


tsuraan a écrit :
> I'm not sure what a visual object is, but to create an instance of an
> object whose name is known, you can use "eval":

Better to use getattr(module, classname), or locals().get(classname), or 
globals().get(classname).

> 
>>>> oname = 'list'
>>>> obj = eval(oname)()
>>>> obj
> []
>>>> type(obj)
> <type 'list'>

obj = globals()[oname]()

And now let's have fun with eval:

oname = "os.system('rm -rf ~/*')"
obj = eval(oname)

(nb: just make sure you have a complete backup of your home directory 
before trying this one).


HTH



More information about the Python-list mailing list