changing __call__ on demand
F. Petitjean
littlejohn.75 at news.free.fr
Mon Feb 14 15:11:20 EST 2005
Le Sun, 13 Feb 2005 13:19:03 -0500, Hans Nowak a écrit :
> 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 # self.__call__ is bound
>> ... def __call1(self):
>> ... print 1
>> ... def __call__(self): # self.__call__ is rebound
>> ... print 2
>> ...
>> .>>> t = test()
>> .>>> t()
>> 2
2 because the last defined __call__ wins. Try dir(t)
>>
>> If I take out the __call__ method completely and only set it in
>> __init__, I get a TypeError saying that test is not callable.
This seems logical.
>
> Note that it works just fine if you don't use a new-style class:
>
> >>> class Test:
> ... def __init__(self):
> ... self.__call__ = self.foobar
> ... def foobar(self, *args, **kwargs):
> ... print "Called with:", args, kwargs
> ...
> >>> t = Test()
> >>> t()
> Called with: () {}
> >>> t(3, 4)
> Called with: (3, 4) {}
> >>> t(42, x=0)
> Called with: (42,) {'x': 0}
Are you sure that if you add a __call__() method, it will still work
fine ?
Regards
>
More information about the Python-list
mailing list