Synthetica
Synthetica

Reputation: 932

Operators for new-style classes

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

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

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 function coerce() is called.

Upvotes: 5

Related Questions