[Python-Dev] Dinamically set __call__ method

alex23 wuwei23 at gmail.com
Wed Nov 5 00:28:43 EST 2014


On 11/04/2014 08:52 AM, Roberto Martínez wrote:
>> I am trying to replace dinamically the __call__ method of an object
>> using setattr.
>> Example:
>>
>> $ cat testcall.py
>> class A:
>>      def __init__(self):
>>          setattr(self, '__call__', self.newcall)
>>
>>      def __call__(self):
>>          print("OLD")
>>
>>      def newcall(self):
>>          print("NEW")
>>
>> a=A()
>> a()
>>
>> I expect to get "NEW" instead of "OLD", but in Python 3.4 I get "OLD".

Given that special methods can only be replaced on the class and not the 
instance, you could create a new version of the class within __init__ 
and assign it to the instance:

     class A:
         def __init__(self, call_method=None):
             if call_method:
		methods = {'__call__': call_method}
                 self.__class__ = type('Custom_A', (A,), )

         def __call__(self):
             return 'original'

     >> a = A()
     >> a()
     "old"
     >> b = A(lambda self: 'new')
     >> b()
     "new"



More information about the Python-list mailing list