(错点)魔方方法__add__与__radd__

如果右操作数的类型是左操作数类型的子类,并且该子类提供了操作的反射方法,则该方法将在左操作数的非反射方法之前被调用。

If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.


这样就解释了左右操作的不同,之前自己老是想着自定义的优先

>>> class Nint(int):

        def __radd__(self,other):

                return int.__sub__(other,self)

>>> a=Nint(5)

>>> b=Nint(3)

>>> 1+b

-2

>>> b+1

4

你可能感兴趣的:((错点)魔方方法__add__与__radd__)