通过类的功能访问多个实例

时间:2020-02-10 15:40:38

标签: python class

如何通过类中的函数同时访问多个实例?

我已经了解了诸如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'

我该如何纠正?

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一次只能将两件事加在一起。

相关问题