python - 在python中做了一类Point,但我不太确定我做错了什么
问题描述
#
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, x, y):
return self.x + self.y
def __sub__(self, x, y):
return self.x - self.y
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)
输出:我得到一个输出,它正在寻找 y 的参数,但我认为我已经将 y 传递给它
Traceback (most recent call last):
File "C:##################################", line 18, in <module>
p3 = p1 + p2
TypeError: __add__() missing 1 required positional argument: 'y'
解决方案
该表达式p3 = p1 + p2
实际上执行为:
p3 = p1.__add__(p2)
使用您当前的函数签名__add__(self, x, y)
,Python 解释器将只接收self
( p1
)、x
( p2
),但会缺少一个参数 ( y
),因此会出现错误:
__add__() missing 1 required positional argument: 'y'
相反,您需要的是一个__add__
实现(sub 也是如此),它将 self 和另一个点实例作为参数,并返回一个新点:
class Point(object):
def __add__(self, other: "Point") -> "Point":
# returns a new point created by adding coordinates
# from self and the other point
推荐阅读
- python - 在函数中传递和返回列表的pythonic方法是什么?
- python - 如何在 Python 中使用根键保存 yaml 键值?
- python - 在 Python 子进程中访问 Lambda 层
- c++ - 具有各种参数的 C++ 模板函数
- php - PHP - 如果 $optional 参数这么说,则捕获所有异常并继续
- amazon-web-services - 如何在我的本地机器的 Docker 中创建现有 EC2(AWS) 的镜像并将其容器化
- python - mypy 无法识别 Dictionary of Dictionary
- database - 如何将嵌入的文档值移动到 MongoDB 中的主文档?
- node.js - 为什么我不能在 Windows 上运行 react-native 应用程序
- makefile - 为什么 Make 更喜欢隐式规则而不是 Makefile 中列出的规则?