I'm trying to implement numpy's ufunc to work with a class, using the __array_ufunc__ method introduced in numpy v1.13.
To simplify, here's what the class could look like :
class toto():
def __init__(self, value, name):
self.value = value
self.name = name
def __add__(self, other):
"""add values and concatenate names"""
return toto(self.value + other.value, self.name + other.name)
def __sub__(self, other):
"""sub values and concatenate names"""
return toto(self.value - other.value, self.name + other.name)
tata = toto(5, "first")
titi = toto(1, "second")
Now if I try to apply np.add between these two, I get the expected result, as np.add relies on add. But if I call say np.exp, I get an error as expected :
>>> np.exp(tata)
AttributeError: 'toto' object has no attribute 'exp'
Now what I would like to do is to "override" all numpy ufuncs to work smoothly with this class without having to redefine every methods (exp(self), log(self), ...) in the class.
I was planning to use numpy ufunc's [__array_ufunc__]1 to do this, but I don't really understand the doc as it doesn't provide a simple exemple of implementation.
If anyone has had any experience with this new functionnality that looks promising, could you provide a simple example ?