generating objects of a type from a name.

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 27 03:46:14 EDT 2007


chris.lyon at spritenote.co.uk a écrit :
> On Jul 27, 1:59 am, tsuraan <tsur... at gmail.com> wrote:
>> 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":
>>
>>>>> oname = 'list'
>>>>> obj = eval(oname)()
>>>>> obj
>> []
>>>>> type(obj)
>> <type 'list'>
>>
>> Hope that helps!
>>
(snip)
> Thanks for that.
> 
> That's the answer.
> 
Nope. That's a Q&D workaround for a lack of knowledge of Python's 
namespaces and lookup rules. The idiomatic solution is top use getattr() 
on the module defining the class:

import visual
clsname = 'sphere'
cls = getattr(visual, clsname, None)
if cls is None:
   print >> sys.stderr, "could not find %s in visual"
else:
   a = cls()

HTH



More information about the Python-list mailing list