Injecting methods into instance / class

Peter Otten __peter__ at
Mon Dec 3 03:34:46 EST 2018

duncan smith wrote:

> On 02/12/2018 18:36, Peter Otten wrote:

>> class CommonMethods:
>>     __add__ = add

> Ah, I could just bind them within the class,
>     mean = mean
>     max = max etc.
> but I'd somehow convinced myself that didn't work. As the names are the
> same I'd probably still prefer to go with something along the lines of
>     for name in ['mean', 'max', ...]:
>         # create a method
> But at least I now have something that works, and I could try something
> like your suggestion above to see if I prefer it.
> The issue was that some of these "functions" are actually callable class
> instances (an attempt to emulate numpy's ufuncs).

For these to work you need to implement the "descriptor protocol", something 

$ cat
from functools import partial

class Add:
    def __call__(self, left, right):
        return 42 + right

    def __get__(self, inst=None, class_=None):
        if inst is None:
            return self
        return partial(self.__call__, inst)

class Demo:
    __add__ = Add()

x = Demo()
print(x + 100)
$ python3

More information about the Python-list mailing list