【发布时间】:2013-10-10 11:34:11
【问题描述】:
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
显然,前两个 print 语句将起作用,而第三个则失败,因为 int.add() 无法处理 C 类实例。
246
125
print 2 + c
TypeError: unsupported operand type(s) for +: 'int' and 'C'
有没有办法解决这个问题,所以 2+c 会导致 C.add() 被调用?
【问题讨论】:
标签: python python-2.7 numbers