class factory

Daniel Klein danielk at aracnet.com
Wed Aug 20 09:07:56 EDT 2003


On 20 Aug 2003 01:15:44 -0700, nick.keighley at marconi.com (Nick
Keighley) wrote:

>I'd like to generate a class on-the-fly from a parameter (a dictionary).


>>> class MyClass(object):
	def __init__(self, deadparrot):
		self.deadparrot = deadparrot

>>> mydict = { 'MyClass' : 'foobar'}   #  { className : constructorArgument }
>>>
>>> className = mydict.keys()[0]
>>> arg = mydict.values()[0]
>>>
>>> myInstance = eval(className + '(arg)')
>>> myInstance
<__main__.MyClass object at 0x00A7DE30>
>>> myInstance.deadparrot
'foobar' 

HTH,

Daniel Klein
Member of the Dead Parrot Society




More information about the Python-list mailing list