Section 98.1: 操作符重载

以下是可以在类中重载的操作符、所需的方法定义以及在表达式中使用操作符的示例。

注意:使用 other 作为变量名不是强制性的,但被认为是一种规范。

Operator Method Expression
+ Addition __add__(self, other) a1 + a2
- Subtraction __sub__(self, other) a1 - a2
* Multiplication __mul__(self, other) a1 * a2
@ Matrix Multiplication __matmul__(self, other) a1 @ a2 (Python 3.5)
/ Division __div__(self, other) a1 / a2 (Python 2 only)
/ Division __truediv__(self, other) a1 / a2 (Python 3)
// Floor Division __floordiv__(self, other) a1 // a2
% Modulo/Remainder __mod__(self, other) a1 % a2
** Power __pow__(self, other[, modulo]) a1 ** a2
<< Bitwise Left Shift __lshift__(self, other) a1 << a2
>> Bitwise Right Shift __rshift__(self, other) a1 >> a2
& Bitwise AND __and__(self, other) a1 & a2
^ Bitwise XOR __xor__(self, other) a1 ^ a2
| (Bitwise OR) __or__(self, other) a1 | a2
- Negation (Arithmetic) __neg__(self) -a1
+ Positive __pos__(self) +a1
~ Bitwise NOT __invert__(self) ~a1
< Less than __lt__(self, other) a1 < a2
<= Less than or Equal to __le__(self, other) a1 <= a2
== Equal to __eq__(self, other) a1 == a2
!= Not Equal to __ne__(self, other) a1 != a2
> Greater than __gt__(self, other) a1 > a2
>= Greater than or Equal to __ge__(self, other) a1 >= a2
[index] Index operator __getitem__(self, index) a1[index]
in In operator __contains__(self, other) a2 in a1
(*args, ...) Calling __call__(self, *args, **kwargs) a1(*args, **kwargs)

用于 __pow__ 的可选参数 modulo 仅用于 pow 内置函数。

每个二进制运算符对应的方法都有一个相应的 “右 ”方法,以__r 开头,例如 __radd__:

class A:
  def __init__(self, a):
    self.a = a

  def __add__(self, other):
    return self.a + other

  def __radd__(self, other):
    print("radd")
    return other + self.a

A(1) + 2 # Out: 3
2 + A(1) # prints radd. Out: 3

操作符重载

以及以 __i 开头的相应就地版本:

class B:
  def __init__(self, b):
    self.b = b

  def __iadd__(self, other):
    self.b += other
    print("iadd")
    return self

b = B(2)
b.b # Out: 2
b += 1 # prints iadd
b.b # Out: 3

操作符重载

由于这些方法并无特别之处,语言的许多其他部分、标准库的某些部分,甚至第三方模块都会自行添加神奇的方法,例如将对象转换为某种类型或检查对象属性的方法。例如,内置的 str() 函数会调用对象的 __str__ 方法(如果存在的话)。下面列出了其中一些用途。

Function Method Expression
Casting to int __int__(self) int(a1)
Absolute function __abs__(self) abs(a1)
Casting to str __str__(self) str(a1)
Casting to unicode __unicode__(self) unicode(a1) (Python 2 only)
String representation __repr__(self) repr(a1)
Casting to bool __nonzero__(self) bool(a1)
String formatting __format__(self, formatstr) "Hi {:abc}".format(a1)
Hashing __hash__(self) hash(a1)
Length __len__(self) len(a1)
Reversed __reversed__(self) reversed(a1)
Floor __floor__(self) math.floor(a1)
Ceiling __ceil__(self) math.ceil(a1)

还有用于上下文管理器的特殊方法 __enter__ 和 __exit__,等等。

Section 98.2: Magic/Dunder Methods

Python 中的 Magic(也称为 dunder,是 double-underscore 的缩写)方法与其他语言中的操作符重载有着类似的作用。当一个类在一元或二元运算符表达式中用作操作数时,它们允许该类定义自己的行为。它们也是一些内置函数调用的实现。

请看二维向量的实现。

import math

class Vector(object):
  # instantiation
  def __init__(self, x, y):
    self.x = x
    self.y = y

  # unary negation (-v)
  def __neg__(self):
    return Vector(-self.x, -self.y)

  # addition (v + u)
  def __add__(self, other):
    return Vector(self.x + other.x, self.y + other.y)

  # subtraction (v - u)
  def __sub__(self, other):
    return self + (-other)

  # equality (v == u)
  def __eq__(self, other):
    return self.x == other.x and self.y == other.y

  # abs(v)
  def __abs__(self):
    return math.hypot(self.x, self.y)

  # str(v)
  def __str__(self):
    return '<{0.x}, {0.y}>'.format(self)

  # repr(v)
  def __repr__(self):
    return 'Vector({0.x}, {0.y})'.format(self)

现在,我们可以在各种表达式中自然地使用向量类的实例。

v = Vector(1, 4)
u = Vector(2, 0)

u + v # Vector(3, 4)
print(u + v) # "<3, 4>" (implicit string conversion)
u - v # Vector(1, -4)
u == v # False
u + v == v + u # True
abs(u + v) # 5.0

Magic/Dunder Methods

Section 98.3: 容器和序列类型

我们可以模拟容器类型,它支持通过键或索引访问值。

请看这个稀疏列表的天真实现,它只存储非零元素,以节省内存。

class sparselist(object):
  def __init__(self, size):
    self.size = size
    self.data = {}

   # l[index]
  def __getitem__(self, index):
    if index < 0:
      index += self.size

    if index >= self.size:
      raise IndexError(index)
      try:
        return self.data[index]
      except KeyError:
        return 0.0

  # l[index] = value
  def __setitem__(self, index, value):
    self.data[index] = value

  # del l[index]
  def __delitem__(self, index):
    if index in self.data:
      del self.data[index]

  # value in l
  def __contains__(self, value):
    return value == 0.0 or value in self.data.values()

    # len(l)
  def __len__(self):
    return self.size

  # for value in l: ...
  def __iter__(self):
    return (self[i] for i in range(self.size)) # use xrange for python2

然后,我们就可以像使用普通列表一样使用 sparselist。

l = sparselist(10 ** 6) # list with 1 million elements
0 in l # True
10 in l # False

l[12345] = 10
10 in l # True
l[12345] # 10

for v in l:
  pass # 0, 0, 0, ... 10, 0, 0 ... 0

容器和序列类型

Section 98.4: 可调用类型

class adder(object):
  def __init__(self, first):
    self.first = first

  # a(...)
  def __call__(self, second):
    return self.first + second

add2 = adder(2)
add2(1) # 3
add2(2) # 4

可调用类型

Section 98.5: 处理未实现的行为

如果您的类没有为所提供的参数类型实现特定的重载操作符,它应该 return NotImplemented (注意,这是一个特殊常量,与 NotImplementedError不同)。这将允许 Python 回退到尝试其他方法来使操作生效:

当返回 NotImplemented 时,解释器将尝试其他类型的反射操作,或其他回退操作,这取决于操作符。如果所有尝试的操作都返回 NotImplemented,解释器将引发相应的异常。

例如,在给定 x + y 的情况下,if x.__add__(y) 返回未实现,y.__radd__(x) 将被替代。

class NotAddable(object):

  def __init__(self, value):
    self.value = value

  def __add__(self, other):
    return NotImplemented

class Addable(NotAddable):

  def __add__(self, other):
    return Addable(self.value + other.value)

  __radd__ = __add__

处理未实现的行为

由于这是反射方法,我们必须实现 __add__ 和 __radd__,才能在所有情况下获得预期的行为;幸运的是,在这个简单的示例中,它们都在做同样的事情,我们可以走捷径。

使用中

>>> x = NotAddable(1)
>>> y = Addable(2)
>>> x + x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NotAddable' and 'NotAddable'
>>> y + y
<so.Addable object at 0x1095974d0>
>>> z = x + y
>>> z
<so.Addable object at 0x109597510>
>>> z.value
3

处理未实现的行为