changing __call__ on demand
Alan McIntyre
alan.mcintyre at esrgtech.com
Sun Feb 13 12:01:20 EST 2005
I tried this:
>>>class test(object):
... def __call1(self):
... print 1
... __call__ = __call1
...
>>>t = test()
>>>t()
1
>>>
Is that what you were looking for?
--
Alan McIntyre
ESRG LLC
http://www.esrgtech.com
Stefan Behnel wrote:
> Hi!
>
> This somewhat puzzles me:
>
> Python 2.4 (#1, Feb 3 2005, 16:47:05)
> [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
> .>>> class test(object):
> ... def __init__(self):
> ... self.__call__ = self.__call1
> ... def __call1(self):
> ... print 1
> ... def __call__(self):
> ... print 2
> ...
> .>>> t = test()
> .>>> t()
> 2
>
> If I take out the __call__ method completely and only set it in
> __init__, I get a TypeError saying that test is not callable.
>
> I want to use this in order to provide different implementations based
> on the object configuration. Calculating the right function to call is
> non-trivial and calls are frequent, so I want to change __call__ in
> order to run the right function directly.
>
> I know, I could use another level of indirection:
>
> def __call__(self):
> self.the_right_method()
>
> and then set the_right_method accordingly, but I find that somewhat
> sub-optimal. Is there a way to change __call__ after class creation?
>
> Stefan
More information about the Python-list
mailing list