如何获得调用

2024-04-18 08:49:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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类实例。在

^{pr2}$

有没有办法绕过这个问题,所以2+c会导致调用c.add()?在


Tags: selfaddnumberreturnifobjectinitvalue
2条回答

{需要处理^ a1}的情况:

def __radd__(self, other):
    if isinstance(other, C):
        return other.value + self.value
    if isinstance(other, Number):
        return other + self.value
    return NotImplemented

注意,不应该引发异常;而是返回NotImplemented单例。这样,另一个对象仍然可以尝试为您的对象支持__add__或{},并且还将有机会实现加法。

当您尝试添加两个类型ab,Python首先尝试调用a.__add__(b);如果该调用返回NotImplemented,则尝试使用b.__radd__(a)

演示:

^{pr2}$

您需要在类上实现__radd__

def __radd__(self, other):
    return self.value + other

这是自动调用的,因为int类将引发NotImplemented错误

相关问题 更多 >