I am writing a class for which objects are initialised with two parameters (a
, b
). The intention is to assign instances of this class to variables so that I can have an equation written symbolically in Python code, but have operator overloading perform unique operations on a
and b
.
import numpy as np
class my_class(object):
def __init__(self, a, b):
self.value1 = a
self.value2 = b
# Example of an overloaded operator that works just fine
def __mul__(self, other):
new_a = self.value1 * other
new_b = self.value2 * np.absolute(other)
return my_class(new_a, new_b)
if __name__ == "__main__":
my_object = my_class(100, 1)
print(np.exp(my_object)) # This doesn't work!
In running the above example code, I encountered the following output:
TypeError: loop of ufunc does not support argument 0 of type my_class which has no callable exp method
Through guesswork, I was able to see that a complaint about no callable exp method
probably meant I needed to define a new method in my class:
def exp(self):
new_val1 = np.exp(self.value1)
new_val2 = np.absolute(new_val1) * self.value2
return my_class(new_val1, new_val2)
which ended up working just fine. But now I will have to write another method for np.expm1()
and so on as I require. Thankfully I only need np.exp()
and np.log()
to work, but I also tried math.exp()
on my object and I started getting a type error.
So now my question is:
The custom exp
method in the class seemed to work for overloading the NumPy function, but how am I supposed to handle math.exp()
not working? It must be possible because somehow when calling math.exp()
on a NumPy array, NumPy understands that a 1-element array can be turned into a scalar and then passed to math.exp()
without issue.
I mean I guess this technically is about overloading a function, but before I realised defining a new exp
was the fix to my first problem, I had no idea why a method like __rpow__
wasn't being called.