python - 新型类的运算符

标签 python class python-2.7 operator-overloading

谁能向我解释为什么 A()+A() 会报错,而 B()+B() 会按预期工作?我在编写较大的代码时遇到了这个问题,但这似乎是重现它所需的最小代码。

from types import MethodType

D = {'__add__': lambda x, y: "".join((repr(x), repr(y)))}

class A(object):
    def __getattr__(self, item):
        if item == '__coerce__':
            raise AttributeError()
        return MethodType(D[item], self)
    def __repr__(self):
        return "A"

class B():
    def __getattr__(self, item):
        if item == '__coerce__':
            raise AttributeError()
        return MethodType(D[item], self)
    def __repr__(self):
        return "B"

try:
    A()+A()
except Exception as e:
    print e

B()+B()

谁有解释吗?

最佳答案

那是因为新样式类从不使用二元运算符调用 __coerce__。同样对于特殊方法 __getattr__ 永远不会在新样式类中调用:来自数据模型 coercion rules :

New-style classes (those derived from object) never invoke the __coerce__() method in response to a binary operator; the only time __coerce__() is invoked is when the built-in function coerce() is called.

关于python - 新型类的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925057/

相关文章:

python - 现有数据帧上的快速傅里叶变换显示出意想不到的结果

c++ - 使用其他类对象的数组类

python - 如何捕获此 Python 异常 : error: [Errno 10054] An existing connection was forcibly closed by the remote host

python - 更快的 SciPy 优化

python - 取消绑定(bind)封闭范围引用的名称

python - 我的 python 程序运行得非常慢

javascript - 更改部分属性

python - 从 Python 2 升级到 Python 3 后该怎么办?

python - 哪些单词在数据集中经常一起出现?

python - 将多个绘图包装在一个图像中