Python:__ add__和+,与float和integer不同的行为 [英] Python: __add__ and +, different behavior with float and integer

查看:174
本文介绍了Python:__ add__和+,与float和integer不同的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将整数值添加到浮点值时,我意识到 __ add __ 方法可以在浮点数上正常运行,例如:

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

起初我以为 __ add __ 只是针对 int float 类型(例如接受float类型)的实现方式有所不同被添加到int类型,但不是相反)。然后我注意到,如果我改用+运算符,则一切正常:

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

有人知道为什么会这样吗? __ add __ + 彼此之间没有很深的联系吗?

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

推荐答案

a + b 不能直接转换为 a .__ add __(b)。如果 a .__ add __ 不存在或返回 b .__ radd __(a) > NotImplemented ,或者如果 b a 类型的子类型的实例

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.

这篇关于Python:__ add__和+,与float和integer不同的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆