首页 > 解决方案 > 在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'

标签: pythonpython-3.8

解决方案


该表达式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

推荐阅读