substitution of a method by a callable object

netimen netimen at gmail.com
Wed Oct 22 15:42:04 EDT 2008


On 22 окт, 20:46, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> 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

thanks!



More information about the Python-list mailing list