Section 201.1: 运算符重载

Python 中的一切都是对象。每个对象都有一些特殊的内部方法,这些方法用于与其他对象进行交互。通常,这些方法遵循 __action__ 的命名约定。总体而言,这被称为 Python 数据模型。

您可以重载这些方法中的任何一个。这在 Python 中的运算符重载中非常常见。以下是使用 Python 数据模型进行运算符重载的示例。Vector 类创建了一个包含两个变量的简单向量。我们将通过运算符重载为两个向量的数学运算提供适当的支持。

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

  def __add__(self, v):
    # Addition with another vector.
    return Vector(self.x + v.x, self.y + v.y)

  def __sub__(self, v):
    # Subtraction with another vector.
    return Vector(self.x - v.x, self.y - v.y)

  def __mul__(self, s):
    # Multiplication with a scalar.
    return Vector(self.x * s, self.y * s)

  def __div__(self, s):
    # Division with a scalar.
    float_s = float(s)
    return Vector(self.x / float_s, self.y / float_s)

  def __floordiv__(self, s):
    # Division with a scalar (value floored).
    return Vector(self.x // s, self.y // s)

  def __repr__(self):
    # Print friendly representation of Vector class. Else, it would
    # show up like, <__main__.Vector instance at 0x01DDDDC8>.
    return '<Vector (%f, %f)>' % (self.x, self.y, )

a = Vector(3, 5)
b = Vector(2, 7)

print a + b # Output: <Vector (5.000000, 12.000000)>
print b - a # Output: <Vector (-1.000000, 2.000000)>
print b * 1.3 # Output: <Vector (2.600000, 9.100000)>
print a // 17 # Output: <Vector (0.000000, 0.000000)>
print a / 17 # Output: <Vector (0.176471, 0.294118)>

上述示例展示了基本数值运算符的重载。完整的列表可以在这里找到。