I am using Python and I am trying to construct a class, say Numbers, using Subclassing ndarray. I wish my class satisfies two following properties:
- All the methods of
numpyis applicable to my classNumbers. (This is the reason why I chose to use Subclassing ndarray.) - Every times I perform the addition between two instances of class
Numbers, I can cumulatively record the number of additions I have used.
Here is what I tried
import numpy as np
class Numbers(np.ndarray):
nb_add = 0
def __new__(cls, values):
self = np.asarray(values).view(cls)
return self
def __add__(self, new_numbers):
Numbers.nb_add = len(new_numbers)
return self new_numbers
a = Numbers([1,2,3,4])
b = Numbers([5,6,7,8])
c = a b
print(a.reshape(2, 2)) # expect [[1,2], [3,4]]
print(Numbers.nb_add)# expect 4 = number of addtions
But the method __add__ leads to error.
I found a similar post here, but it is not the case I am looking for.
Could anyone help me? Thanks!
CodePudding user response:
The problem is that the expression self new_numbers is referencing the __add__ method of Numbers and hence the method calls itself.
If you explicitly call the __add__ method of the base class, then you get the result you want:
import numpy as np
class Numbers(np.ndarray):
nb_add = 0
def __new__(cls, values):
self = np.asarray(values).view(cls)
return self
def __add__(self, new_numbers):
Numbers.nb_add = len(new_numbers)
return np.ndarray.__add__(self,new_numbers)
a = Numbers([1,2,3,4])
b = Numbers([5,6,7,8])
c = a b
print(a.reshape(2, 2)) # expect [[1,2], [3,4]]
print(Numbers.nb_add)# expect 4 = number of addtions
