Python - 自引用 class(使用魔术运算符的向量加法)

Python - self-referencing class (Vector addition using magic operators)

我无法理解此 class 的自我引用在这段代码中的工作原理:

class Vector2D:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __add__(self, other):
    return Vector2D(self.x + other.x, self.y + other.y)

first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x)
print(result.y)

-- 只是为了检查我是否理解魔术方法的工作原理,在 result = first + second 中,参数 other 指的是 second 对吗?

--编辑: 谢谢,我想这消除了我对 other 的困惑。 我仍然不明白这条线是如何工作的:return Vector2D(self.x + other.x, self.y + other.y) 即 class Vector2D 在其中被引用

the argument other refers to second, right?

正确。您可以在 __add__:

中使用 print 进行验证
class Vector2D:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __add__(self, other):
      print(other.x, other.y)
      return Vector2D(self.x + other.x, self.y + other.y)

first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second

>> 3 9

是的,这相当于:

result = first.__add__(second)

所以:

  1. selffirst
  2. othersecond
  3. result 是新的 Vector2D

是的,other是右边的表达式结果,在你的例子中是second

来自object.__add__() documentation

For instance, to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, x.__add__(y) is called.

表达式 Vector2D(self.x + other.x, self.y + other.y) 创建了 class 的新实例,其中 xy 的新值是根据当前实例的总和构造的xy 以及右侧实例的相同属性。

创建了一个新实例,因为 + 的正常语义是 return 一个新实例,而操作数本身保持不变。将此与添加两个列表 (['foo', 'bar'] + ['bar', 'baz']) 进行比较;还有一个新的列表对象 returned.