我无法理解此类的自引用如何在此代码中运行:
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
答案 0 :(得分:3)
是的,这相当于:
result = first.__add__(second)
这样:
self
是first
other
是second
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
的新值创建类的新实例,这些值是根据当前实例y
和x
和右侧实例上的相同属性。
创建一个新实例是因为y
的正常语义是返回一个新实例,而操作数本身保持不变。将此与两个列表相加(+
);还返回了一个新的列表对象。