1

consider my class mint

class mint(object):
    def __init__(self, i):
        self.i = i

    def __add__(self, other):
        o = other.i if isinstance(other, mint) else other
        return mint(1 + self.i + o)

    def __repr__(self):
        return str(self.i)

It's designed to do another kind of addition.

a = mint(1)

a + 1 + 2

6

However, adding while my object is on the right doesn't work.

1 + a
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-519-8da568c0620a> in <module>()
----> 1 1 + a
TypeError: unsupported operand type(s) for +: 'int' and 'mint'

Question: How do I modify my class such that 1 + a will work?

piRSquared
  • 285,575
  • 57
  • 475
  • 624

2 Answers2

1

You can use __radd__:

class mint(object):
    def __init__(self, i):
        self.i = i

    def __add__(self, other):
        o = other.i if isinstance(other, mint) else other
        return mint(1 + self.i + o)

    def __repr__(self):
        return str(self.i)

    def __radd__(self, other):
        return self + other

a = mint(1)
print(1 + a)

Output:

3

Here's explanation from Python docs:

These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. [2] For instance, to evaluate the expression x - y, where y is an instance of a class that has an rsub() method, y.rsub(x) is called if x.sub(y) returns NotImplemented.

niemmi
  • 17,113
  • 7
  • 35
  • 42
1

Implement __radd__

In [1]: class mint(object):
   ...:     def __init__(self, i):
   ...:         self.i = i
   ...: 
   ...:     def __add__(self, other):
   ...:         o = other.i if isinstance(other, mint) else other
   ...:         return mint(1 + self.i + o)
   ...: 
   ...:     def __repr__(self):
   ...:         return str(self.i)
   ...:         
   ...:     def __radd__(self, other):
   ...:         return self.__add__(other)
   ...:     

In [2]: a = mint(1)

In [3]: 1 + a
Out[3]: 3
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172