Python - 自引用类(使用魔术运算符添加矢量)

时间:2016-08-15 10:29:21

标签: python class python-3.x magic-methods

我无法理解此类的自引用如何在此代码中运行:

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)即在其中引用的类Vector2D

3 个答案:

答案 0 :(得分:3)

是的,这相当于:

result = first.__add__(second)

这样:

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

答案 1 :(得分:1)

  

参数other是指second,对吗?

正确。您可以使用print内的__add__验证:

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

答案 2 :(得分:1)

是的,other是您手边的右侧表达式结果{1}}。

来自object.__add__() documentation

  

例如,要评估表达式second,其中x + y是具有x方法的类的实例,则会调用__add__()

表达式x.__add__(y)使用Vector2D(self.x + other.x, self.y + other.y)x的新值创建类的新实例,这些值是根据当前实例yx和右侧实例上的相同属性。

创建一个新实例是因为y的正常语义是返回一个新实例,而操作数本身保持不变。将此与两个列表相加(+);还返回了一个新的列表对象。