class C(object):
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, C):
return self.value + other.value
if isinstance(other, Number):
return self.value + other
raise Exception("error")
c = C(123)
print c + c
print c + 2
print 2 + c
Run Code Online (Sandbox Code Playgroud)
显然,前两个打印语句将起作用,而第三个语句失败,因为 int. add () 不能处理一个 C 类实例。
246
125
print 2 + c
TypeError: unsupported operand type(s) for +: 'int' and 'C'
Run Code Online (Sandbox Code Playgroud)
有没有办法来解决这个问题,所以2 + C会导致C.加()被调用?