我有一个简单的程序:
class Coordinate(object):
def __init__(self, x , y):
self.x = x
self.y = y
def distance (self, other):
x_diff = (self.x-other.x)**2
y_diff = (self.y - other.y)**2
return (x_diff+y_diff)**0.5
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"
def __sub__(self,other):
return Coordinate(self.x - other.x,self.y - other.y)
c = Coordinate (3,4)
o = Coordinate (1,1)
c - o
给了我<2,3>
。
现在,如果我将__sub__()
更改为:
def __sub__(self,other):
return self.x - other.x
并运行程序:
c - o
仍然给我<2,3>
而不是2
。
答案 0 :(得分:0)
为我工作。
class Coordinate(object):
def __init__(self, x , y):
self.x = x
self.y = y
def distance (self, other):
x_diff = (self.x-other.x)**2
y_diff = (self.y - other.y)**2
return (x_diff+y_diff)**0.5
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"
def __sub__(self,other):
return self.x- other.x
c= Coordinate (3,4)
o = Coordinate (1,1)
c - o
输出
2
答案 1 :(得分:0)
如您所见,它返回2。您可能做错了什么。看图片 code running