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)
有人有解释吗?