Let say I have a python class A
:
class A:
def __init__(self, matrix, metadata: list):
self.matrix = np.array(matrix)
self.metadata = metadata
#...
Now I want all arithmetic operations work for my class. They supposed to simply translate the operation to matrix
, i.e. like so:
def __add__(self, other):
if isinstance(other, type(self)):
raise ValueError("Not allowed.")
else:
return A(
matrix=self.matrix.__add__(other),
metadata=self.metadata,
)
Now the problem is that I have to repeate almost the same code for each arithmetic magic function, i.e __add__, __sub__, __mul__, __truediv__, __pow__, __radd__, __rsub__, __rmul__, __rtruediv__, __iadd__, __isub__, __imul__, __itruediv__, __abs__, __round__, __floor__, __ceil__, __trunc__
. Which leads to a lot of repeating code.
How can I define them dynamically in a for loop? like
magic_functions = ["__add__", "__sub__", ...]
for magic_function in magic_functions:
# define the method and add it to the class