我的代码中不断出现这个错误.为什么这种情况不断发生?谢谢



这是一个方法重载

class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.coords = (self.x, self.y)

def move(self, x, y):
self.x += x
self.y += y

def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
def __mul__(self, p):
return (self.x * p.x + self.y * p.y)


def __str__(self):  
return  str(self.x)  str(self.y)
p1 = Point(3,4)
p2 = Point(3,2)
p3 = Point(1,3)
p4 = Point(0,1)
p5 = p1 + p2
p6 = p4 - p1
p7 = p2*p3
print(p5, p6, p7)

我总是犯这个错误。有人能解释一下为什么语法不正确吗

return str(self.x(str(self.y(^SyntaxError:语法无效

这不会返回字符串

return  str(self.x),  str(self.y)

您应该将其作为字符串返回

return  "(" + str(self.x) + ", " + str(self.y) + ")"

无效语法是因为您试图返回两个变量,需要用逗号分隔它们。

def __str__(self):  
return  str(self.x),  str(self.y)

相关内容

最新更新