Operators for new-style classes

Can someone explain to me why A()+A()it gives an error, but it B()+B()works as expected? I came across this when I wrote most of the code, but this is apparently the smallest code needed to play 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?

+4
source share
1 answer

This is because new style classes are never called __coerce__with binary operators. Also, for special methods, it is __getattr__never called in new style classes: from the data model, enforcement rules :

(, ) __coerce__() ; __coerce__(), coerce().

+5

All Articles