Adding a float to an integer using a method (not an operator) [duplicate]

天大地大妈咪最大 提交于 2020-01-25 06:47:09

问题


I was expecting __add__ to work, but that's obviously not the case (in Python 3.8.0 at least):

>>> 10 .__add__(5.5)  
NotImplemented
>>> 10 .__radd__(5.5) 
NotImplemented

The other way around works:

>>> 5.5 .__add__(10)  
15.5
>>> 5.5 .__radd__(10)  
15.5

Why doesn't the first code work? Is there a good reason behind it?

If those methods don't work, then what method is used by "syntactic sugar" operations such as 10 + 5.5 or 10 - 5.5?

来源:https://stackoverflow.com/questions/59644166/adding-a-float-to-an-integer-using-a-method-not-an-operator

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