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?
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 +=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With