Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition between 'int' and custom class [duplicate]

I was experimenting around with dunders in python when I found something: Say I created a class:

class MyInt:
    def __init__(self, val):
        self.val = val

    def __add__(self, other):
        return self.val + other

a = MyInt(3)

The __add__ works perfectly fine when this is run:

>>> print(a + 4)
7

However, when I ran this:

>>> print(4 + a)
TypeError: unsupported operand type(s) for +: 'int' and 'MyInt'

I know that the int class does not support adding with MyInt, but are there any workarounds for this?

like image 652
Paul Avatar asked Aug 28 '20 16:08

Paul


1 Answers

This is what the __radd__ method is for - if your custom object is on the right side of the operator, and the left side of the operator can't handle it. Note that the left side of the operator will take precedence, if possible.

>>> class MyInt:
...     def __init__(self, val):
...         self.val = val
...     def __add__(self, other):
...         return self.val + other
...     def __radd__(self, other):
...         return self + other
... 
>>> a = MyInt(3)
>>> print(a + 4)
7
>>> print(4 + a)
7

The third 'hidden' method you can override, for any given operator, will be __iadd__, which corresponds to the assignment operator +=.

like image 99
Green Cloak Guy Avatar answered Sep 18 '22 17:09

Green Cloak Guy