changing __call__ on demand
Steven Bethard
steven.bethard at gmail.com
Sun Feb 13 12:42:17 EST 2005
Stefan Behnel wrote:
> Is there a way to change __call__ after class creation?
Check out this thread on the topic:
http://mail.python.org/pipermail/python-list/2004-January/203142.html
Basically, the answer is no -- at least not on a per-instance basis.
You can try something like:
py> class Test(object):
... def __new__(cls):
... cls.__call__ = cls.call1
... return object.__new__(cls)
... def call1(self):
... print 'call1'
... def __call__(self):
... print '__call__'
...
py> Test()()
call1
But then the call method is changed for all instances:
py> class Test(object):
... instances = 0
... def __new__(cls):
... if cls.instances == 1:
... print "setting __call__"
... cls.__call__ = cls.call1
... cls.instances += 1
... return object.__new__(cls)
... def call1(self):
... print 'call1'
... def __call__(self):
... print '__call__'
...
py> t1 = Test()
py> t1()
__call__
py> t2 = Test()
setting __call__
py> t2()
call1
py> t1()
call1
Steve
More information about the Python-list
mailing list