小编use*_*402的帖子

如何调用 __add__

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.()被调用?

python numbers python-2.7

2
推荐指数
1
解决办法
548
查看次数

标签 统计

numbers ×1

python ×1

python-2.7 ×1