2016-04-30 56 views
0

所以我有一个学校项目,我们需要为GPS系统做几个类。我有一个问题搞清楚函数dist(self,other):显示在我的代码底部。项目后期的其他定义很大程度上依赖于它,但我很困惑这一点。位于dist函数计算的曼哈顿距离(X1-X2)+通过实例变量Xÿ定义的位置的(Y1-Y2),和另一个位置其他其被给定为一个元组python - 麻烦计算manhatan距离,TypeError

class GPS_Location: 
    def __init__(self,x,y): 
     self.x=x 
     self.y=y 
    def __str__(self): 
     return '(%s,%s)' % (self.x,self.y) 
    def __repr__(self): 
     return 'GPS_Location(%s,%s)' % (self.x,self.y) 
    def __eq__(self,other): 
     self.other = other 
     if (self.x,self.y) == other: 
      return True 
     else: 
      return False 
    def dist(self,other): 
     self.other = other 
     return abs(self.x - (other[0])) + abs(self.y - (other[1])) #TypeError 

当测试代码时,我不断收到“TypeError:'GPS_Location'对象不可迭代”。我已经尝试了很多次的调整,但我无法弄清楚我做错了什么。

任何帮助将不胜感激!

+0

请将您的代码添加为代码格式的文本,而不是链接到图像。 – TigerhawkT3

+0

您还应该添加生成错误的代码。什么是“位置”对象? – Francesco

+0

注意:为什么在'dist'和'__eq__'中都写'self.other = other'而没有使用它(你用'other'参数调用这两个函数并在你的代码中使用'other')?或者你在别的地方使用它? – quapka

回答

0
  1. 确保第8行像其他方法一样缩进4个空格。
  2. 似乎没有任何理由将other指定为self.other,__eq__()dist()
  3. 你可能有可能与你是如何调用这些方法唯一的其他问题(你提到的说法other只是一个元组),这个工程:

    x = GPS_Location(1, 1) 
    x == (1, 1) 
    # True 
    x == (2, 2) 
    # False 
    x.dist((1, 1)) 
    # 0 
    x.dist((2, 2)) 
    # 2 
    

如果您实际上需要通过第二GPS_Locationother参数dist,则需要进行如下更新:

def dist(self, other): 
    return abs(self.x - other.x) + abs(self.y - other.y) 

呼叫它是这样的:

x = GPS_Location(1, 1) 
y = GPS_Location(2, 2) 
x.dist(y) 
# 2