osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Injecting methods into instance / class


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 
like

$ cat tmp.py
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 tmp.py
142