pythonfloating-pointintegeraddition

Python: __add__ and +, different behavior with float and integer


When adding an integer value to a float value, I realized that __add__ method is working fine if called on float, such as this:

>>> n = 2.0
>>> m = 1
>>> n.__add__(m)
3.0

but not if called on an integer:

>>> m.__add__(n)
NotImplemented

At first I thought that __add__ was just being implemented differently for int and float types (like float types accepting to be added to int types, but not the opposite). Then I noticed that everything works fine if I use the + operator instead:

>>> n + m
3.0
>>> m + n
3.0

Does anybody know why this is happening? Are __add__ and + not deeply related to each other?


Solution

  • a + b does not directly translate to a.__add__(b). It also tries b.__radd__(a) if a.__add__ doesn't exist or returns NotImplemented, or if b is an instance of a subtype of a's type.