谁能向我解释为什么 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 functioncoerce()
is called.
关于python - 新型类的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925057/