python - Can addition between classes be evaluated by the class of the 2nd argument? -


this question has answer here:

i've defined new modulus 7 class:

class mod7:      def __init__(self, n):         self.val = n % 7      def __repr__(self):         return str(self.val) 

then

in [2]: = mod7(18)  in [3]: out[3]: 4    

i wanted allow additions of not mod7 objects of integers new class. under class i've added

    def __add__(self, other):         if type(other) int:             return mod7(self.val + other)         if type(other) mod7:             return mod7(self.val + other.val) 

and

in [11]: + mod7(5) out[11]: 2  in [12]: + 5 out[12]: 2 

however

in [13]: 5 + traceback (most recent call last):    file "<ipython-input-13-14fd8adcbf4d>", line 1, in <module>     5+a  typeerror: unsupported operand type(s) +: 'int' , 'mod7' 

i understand why - addition function called class of 1st argument. question: there way override 5 + a according class of 2nd argument, i.e. a?

you'll want define __radd__. called automatically if left operand did not support +, ints do, have define handle situation. can define call __add__ function don't have rewrite anything.


Comments