简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM