0

Is there a way to do arithmetic on python class objects, and all the operations will be applied to one attribute automatically. For example:

>>> x = Struct(__data__ = [100,100])
>>> y = Struct(__data__ = [200,200])
>>> x + y
Struct(__data__ = [300,300])
>>> np.array(x) + np.array(y)
np.array(Struct(__data__ = [300,300]))
>>> x += y
x ==> Struct(__data__ = [300,300])
>>> x[1:] = 50
x ==> Struct(__data__ = [300,50])

I want it to perform like a normal number/array, and all the operations apply to .__data__ automatically.

small
  • 25
  • 5
  • Does this answer your question? [Overloading Addition, Subtraction, and Multiplication Operators](https://stackoverflow.com/questions/20507745/overloading-addition-subtraction-and-multiplication-operators) – Josh Clark Apr 17 '20 at 16:13
  • Thanks for the useful link, and I am currently doing this, just feel there should be an easier way to handle such a common problem. – small Apr 17 '20 at 19:23

1 Answers1

0

Yes it's possible. You need to define you dunder or magic methods__add__, __mul__, __eq__ etc for your class.

NomadMonad
  • 651
  • 6
  • 12