【问题标题】:Must I override integer __add__ method to support addition of an integer and object?我必须覆盖整数 __add__ 方法以支持整数和对象的加法吗?
【发布时间】:2019-09-08 17:25:43
【问题描述】:

所以我正在制作一个名为 Complex 的类,它表示虚数(我知道 python 有它自己的,但我想自己制作一个)。事情是我想构建一个支持复数和整数相加的 add 方法。所以:

a = Complex(2, 4) + Complex(1, 1)
b = Complex(0, 3) + 3
c = 2 + Complex(4, 5)

应该都支持。据我了解,

object1 + object2

是语法糖等价的

object1.__add__(object2)

第一个和第二个例子都很好,但我如何让我的班级支持 INTEGER + COMPLEX 形式的加法?如果需要,我是否必须覆盖整数 __add__ 方法;我该怎么做,还有其他方法吗?

【问题讨论】:

    标签: python add magic-methods


    【解决方案1】:

    你必须在Complex上实现__radd__

    这种工作方式非常酷,如果__add__ 的对象上没有现有实现,在你的情况下,int + Complex,python 将自动检查__radd__ 是否在右手对象。

    所以它会是这样的:

    - does `int` have `__add__` for `Complex`? no
    - does `Complex` have `__radd__` for `int`? yes. cool, we've solved it
    

    实现可能类似于:

    class Complex:
        def __radd__(self, other):
            return self + Complex(other)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多