En Thu, 24 Jan 2008 05:11:19 -0200, kramer31 <[EMAIL PROTECTED]>  
escribió:

> Can anyone tell me if there is a way in python that I can implement a
> factory function which takes as input a string ClassName and returns
> an object of type ClassName?

def InstanceFactory(classname):
     cls = globals()[classname]
     return cls()

If the class resides in a different module:

def InstanceFactory(modulename, classname):
     if '.' in modulename:
         raise ValueError, "can't handle dotted modules yet"
     mod = __import__(modulename)
     cls = getattr(mod, classname]
     return cls()

I suppose you get the names from a configuration file or something -  
usually it's better to just pass the class instead of the class name.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to