substitution of a method by a callable object

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Oct 22 18:46:22 CEST 2008


netimen a écrit :
> Can I substitute a method of a class by a callable object (not a
> function)? I can very easy insert my function in a class as a method,
> but an object - can't.

functions implement the descriptor protocol so when looked up as class 
attributes, the lookup invoke their __get__ method, which in turn 
returns a method object (which is a thin wrapper around the function, 
the class and the instance).

You can either build the method manually (as Georges explained), or make 
your own Obj class a proper descriptor:

from types import MethodType

class Obj(object):
      __name__ = "Obj" # for Method.__repr_

     def __call__(self, obj_self):
         print 'Obj'

     def __get__(self, instance, cls):
         return MethodType(self, instance, cls)


HTH



More information about the Python-list mailing list