This sounds kind of stupid but I'm not talking about 1 + 2 = 2 + 1
. I am talking about where an object with an __add__
method is added to a number. An example will be:
>>> class num:
... def __add__(self,x):
... return 1+x
...
>>> n = num()
>>> 1+n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
>>> n+1
2
>>>
I don't understand why the first one returns an error and the second one works like normal
Addition isn't assumed to be commutative - for example, [1] + [2] != [2] + [1]
- so there's a separate method you need to implement when your object is on the right side of a +
and the thing on the left doesn't know how to handle it.
def __radd__(self, other):
# Called for other + self when other can't handle it or self's
# type subclasses other's type.
Similar methods exist for all the other binary operations, all named by sticking an r
in the same place.
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