如何通过类中的函数同时访问多个实例?
我已经了解了诸如other
之类的参数,但是如果我有3个对象并且需要在同一函数中同时访问它们,该怎么办?
这是我要更正的代码:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other, other_1):
return Vector2D(self.x + other.x + other_1.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
third = Vector2D(1, 1)
result = first + second + third
print(result.x)
print(result.y)}
它显示以下错误:
TypeError: __add__() missing 1 required positional argument: 'other_1'
我该如何纠正?
答案 0 :(得分:1)
只需删除other_1
参数:
>>> 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)
>>> third = Vector2D(1, 1)
>>> result = first + second + third
>>>
>>> print(result.x)
9
>>> print(result.y)
17
这个想法是first + second + third
等同于(first + second) + third
。 Python一次只能将两件事加在一起。