Redefining __call__ in an instance

Robert Brewer fumanchu at amor.org
Fri Jan 16 01:16:20 CET 2004


Robert Ferrell wrote:
> I'd like to have a factory class that takes a string argument 
> and returns
> the appropriate factory method based on that string.  I'd like the
> instances to be callable.  Like this:
> 
> fact = Factory('SomeThing')
> aSomeThing = fact(some args)
> 
> anotherFact = Factory('SomeThingElse')
> anotherThing = anotherFact(some other args)

Perhaps this will give you some ideas:

>>> class SomeThing(object):
... 	pass
... 
>>> def Factory(classname, *args, **kwargs):
... 	return globals()[classname](*args, **kwargs)
... 
>>> st = Factory('SomeThing')
>>> st
<__main__.SomeThing object at 0x010C0F10>


If you still want to package that into a class instead of a function
(and then override __call__), feel free. Obviously, more exception
checking could be done.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list