首页 > 解决方案 > 通过类的函数访问多个实例

问题描述

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

我已经了解了类似的参数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'

我该如何纠正?

标签: pythonclass

解决方案


只需删除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 一次只添加两个东西。


推荐阅读