我无法理解此类的自引用在这段代码中是如何工作的:
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)
所以:
self
是第一个
其他
是第二个
结果
是新的Vector2D
关于Python - 自引用类(使用魔术运算符进行向量加法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953411/