Python - 自引用类(使用魔术运算符进行向量加法)

标签 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 + secondary 中,参数 other 引用 second 对吗?

--编辑: 谢谢,我想这消除了我对其他的困惑。 我仍然不明白这一行是如何工作的: return Vector2D(self.x + other.x, self.y + other.y) 即类 Vector2D 是里面引用了

最佳答案

是的,这相当于:

result = first.__add__(second)

所以:

  1. self第一个
  2. 其他第二个
  3. 结果是新的Vector2D

关于Python - 自引用类(使用魔术运算符进行向量加法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953411/

相关文章:

java - Python 代码中的 Java 排序算法

python - 重新排序 pandas from_product-MultiIndex DataFrame 中的级别以及值?

python - 使用 Popen.stdin 执行多个命令

python , Pandas ;值错误 ('window must be an integer' ,)

java - 确定 .class 文件是否使用调试信息编译?

C++:组合接口(interface)

python - 导入错误: cannot import name 'sync'

c++ - c++ 中的嵌套类

Python 3 : Python/C API String Problems

python - Pandas 中的代码标准化和应用功能花费了太多时间