繁体   English   中英

如何获得__add__的称呼

[英]How to get __add__ called

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语句将起作用,而第三个print语句由于int而失败。 add ()无法处理C类实例。

246
125
    print 2 + c
TypeError: unsupported operand type(s) for +: 'int' and 'C'

有没有办法解决这个问题,所以2 + c会导致C. add ()被调用?

您还需要添加__radd__来处理相反的情况:

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____radd__ ,并且也将有机会实现加法。

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

演示:

>>> from numbers import Number
>>> class C(object):
...     def __init__(self, value):
...         self.value = value
...     def __add__(self, other):
...         print '__add__ called'
...         if isinstance(other, C):
...             return self.value + other.value
...         if isinstance(other, Number):
...             return self.value + other
...         return NotImplemented
...     def __radd__(self, other):
...         print '__radd__ called'
...         if isinstance(other, C):
...             return other.value + self.value
...         if isinstance(other, Number):
...             return other + self.value
...         return NotImplemented
... 
>>> c = C(123)
>>> c + c
__add__ called
246
>>> c + 2
__add__ called
125
>>> 2 .__add__(c)
NotImplemented
>>> 2 + c
__radd__ called
125

您需要在__radd__上实现__radd__

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM