为什么 __sub__ 和 __rsub__ 以这种方式实现 numbers.Complex

Why are __sub__ and __rsub__ implemented and, in this way, for numbers.Complex

我正在查看 numbers 模块中 Complex 的实现,并注意到 __sub____rsub__ 的实现如下所示:

def __sub__(self, other):
    """ self - other """
    return self + -other

def __rsub__(self, other):
    """ other - self """
    return -self + other

这让我很困惑。

首先,我不太确定为什么要实现这些(猜测 Complex 的所有子类都可以回退到它?),其次,我不明白他们为什么选择使用一元 - 这样的实现。

有什么想法吗?

这是 sub类 可以使用的通用实现,是的,如果他们愿意的话。这是一个额外的目标;这些 ABC 类型的主要目标是能够鸭式数字类型(参见 PEP 3141 – A Type Hierarchy for Numbers.

实现使用一元减去避免递归;如果您使用 self - other,则 Python 使用 self.__sub__(other)self.__rsub__(other) 再次

因为减法可以通过一元减法转换为加法,ABC 的作者能够为您提供这些方法作为奖励;另一种方法是提供 @abstracmethod 方法,强制 sub类 提供具体的实现。您的子类现在可以 可选 以不同的方式实现这些方法,如果这更有效的话,但它们 没有

这是标准库提供的所有ABC中使用的模式。如果您查看 documentation for the collections.abc module,您会注意到一个 Mixin Methods 列;这些都是相应 ABC 提供的作为具体实现的所有方法,这些方法可能依赖也可能不依赖该 ABC 或其基础 类.

定义的抽象方法

另请参阅构建 PEP 3141 的一般性 PEP 3119 – Introducing Abstract Base Classes

Some ABCs also provide concrete (i.e. non-abstract) methods; for example, the Iterator class has an __iter__ method returning itself, fulfilling an important invariant of iterators (which in Python 2 has to be implemented anew by each iterator class). These ABCs can be considered "mix-in" classes.