新式课程的操作员

Syn*_*ica 4 python class operator-overloading python-2.7

任何人都可以向我解释为什么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()
Run Code Online (Sandbox Code Playgroud)

有人有解释吗?

Ash*_*ary 5

那是因为新的样式类永远不会__coerce__使用二元运算符调用.对于特殊方法__getattr__,永远不会在新样式类中调用:从数据模型强制规则:

新样式类(从对象派生的类)从不调用 __coerce__()方法来响应二元运算符; __coerce__()调用唯一的时间是调用内置函数coerce().