Python 新样式类的运算符
有谁能解释一下为什么Python 新样式类的运算符,python,class,python-2.7,operator-overloading,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__':
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()
有人对此有什么解释吗?这是因为新样式的类从不使用二进制运算符调用
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>。另外,对于特殊方法,\uuu getattr\uuu
从未在新样式类中调用:从数据模型:
新样式类(从对象派生的样式类)从不调用
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;调用\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu