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

When adding an integer value to the float value, I realized that the __add__ method works fine if called in a float, for example:

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

but not if called by an integer:

 >>> m.__add__(n) NotImplemented 

At first I thought that __add__ just implemented differently for int and float types (for example, float types adding to int types, but not vice versa). Then I noticed that everything was working fine if I use the + operator instead:

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

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

+5
source share
1 answer

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

+6
source

All Articles