Smart factory class

K

kramer31

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?
 
A

Arnaud Delobelle

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')

But why do you want to do this?
 
G

Gabriel Genellina

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top