只需
__radd__在您的类中实现一个方法即可。一旦int类无法处理加法,则
__radd__if实施该加法。
class A(object): def __init__(self, value): self.value = value def __add__(self, other): if isinstance(other, self.__class__): return self.value + other.value else: return self.value + other def __radd__(self, other): return self.__add__(other)a = A(1)print a + 1# 2print 1 + a# 2
例如,如果要返回x,则求值x-y,其中y是具有
__rsub__()方法的类的实例。y.__rsub__(x)``x.__sub__(y)``NotImplemented
同样适用于
x + y。



