[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Smart factory class

kramer31

1/24/2008 7:11:00 AM

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?
2 Answers

Arnaud Delobelle

1/24/2008 7:26:00 AM

0

On Jan 24, 7:11 am, kramer31 <kramer.newsrea...@gmail.com> wrote:
> 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 mkobj(classname, ns=globals()): return ns[classname]()
...
>>> class A: pass
...
>>> mkobj('A')
<__main__.A instance at 0x6bd28>
>>>

But why do you want to do this?

--
Arnaud

Gabriel Genellina

1/24/2008 7:43:00 AM

0

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