python - 通过类的函数访问多个实例
问题描述
如何通过类中的函数同时访问多个实例?
我已经了解了类似的参数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'
我该如何纠正?
解决方案
只需删除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 一次只添加两个东西。
推荐阅读
- powershell - 使用 Add-Content 管道获取内容
- python - Python pow() 函数如何在负幂和 mod 值下工作
- mysql - 如何构建 cron 作业和脚本以执行 sql 命令
- spring-boot - 运行graals原生spring cloud函数示例
- sql - T-SQL:生成数字组合并保存到表中
- angular - Angular / Angular 10 中的递归组件使用
- python - 为什么基于 C 的 Python 扩展总是返回相同的值?
- javascript - 无法逃脱撇号
- laravel - 我的组件没有显示-vuejs-laravel
- java - 在 Apache Tomcat 上运行 Spring-Boot Web App 时出现 500 Servlet 错误 - 无法删除类文件