Smart factory class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Jan 24 02:43:22 EST 2008


En Thu, 24 Jan 2008 05:11:19 -0200, kramer31 <kramer.newsreader at gmail.com>  
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




More information about the Python-list mailing list