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

我们两清 提交于 2020-05-08 08:49:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38624450/python-add-and-different-behavior-with-float-and-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!