Reputation: 932
Could anyone explain to me why A()+A()
does give an error, but B()+B()
works as expected? I came across this when I was writing a larger piece of code, but this seems to be the smallest code necessary to reproduce it.
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()
Does anyone have an explanation?
Upvotes: 4
Views: 70
Reputation: 251196
That's because new style classes never invoke __coerce__
with binary operators. Also for special methods __getattr__
is never invoked in new style classes: From Data model 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.
Upvotes: 5