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
顯然,前兩個打印語句將工作,第三個失敗,因爲int。 add()不能處理一個C類實例。如何獲得__add__調用
246
125
print 2 + c
TypeError: unsupported operand type(s) for +: 'int' and 'C'
有沒有辦法來解決這個問題,所以2 + C會導致C. 添加()被調用?