[Python-Dev] Dinamically set __call__ method

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Nov 9 14:14:07 CET 2014

Gregory Ewing wrote:

> Ethan Furman wrote:
>> And the thing going on is the normal python behavior (in
>> __getattribute__, I believe) of examining the returned attribute to see
>> if it is a descriptor, and if so invoking it.
> Only if you look it up through the instance, though.
> Normally, if you look up an attribute on a class,
> the descriptor protocol doesn't get triggered.

Since this whole thread is about giving instances their own individual
__call__ methods, I don't think that doing the look-up on the class is part
of the requirements :-)

This seems to work for me:

class call_instance(object):
    def __get__(self, obj, cls=None):
        if cls is None:  cls = type(obj)
        if obj is None:  obj = cls
        return obj.my_call

class SomeClass(object):
    __call__ = call_instance()

a = SomeClass()
b = SomeClass()
c = SomeClass()
c.eggs = 23

from types import MethodType
a.my_call = lambda x, y=1: x/y
b.my_call = lambda spam: str(spam).upper()
c.my_call = MethodType(lambda self: self.eggs + 1, c)


More information about the Python-list mailing list