TypeError:distance()只需要2个参数(给定1个)

时间:2017-11-02 00:49:30

标签: python-2.7 python-3.x

我试图通过将参数传递给point class来检查距离。但是当我提供用户输入时,程序稍后在计算距离点时失败:

import math
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance(self, point):
        return math.sqrt((self.x-point.x)**2+ (self.y-point.y)**2)

class Circle(Point):
    @classmethod
    def envelops(self, shape):
        if shape == "Circle":
            r1 = float(input("Enter radius first circle:"))
            r2 = float(input("Enter radius of second circle:"))
            x1 = float(input("Enter first circle's x coordinate: "))
            x2 = float(input("Enter second circle's x coordinate: "))
            y1 = float(input("Enter first circle's y coordinate: "))
            y2 = float(input("Enter second circle's y coordinate: "))
            Point(x1,y1)
            dist=(Point.distance(Point(x2,y2)))
            if r1 > (r2 + dist):
                print "First Circle envelops the second circle"
            else:
                pass



if __name__ == "__main__":
    shape = 'Circle'
    Circle.envelops(shape)

执行文件时出现以下错误:

    dist=(Point.distance(Point(x2,y2)))
TypeError: distance() takes exactly 2 arguments (1 given)

我需要紧急摆脱这个错误。非常感谢。

2 个答案:

答案 0 :(得分:1)

变化:

Point(x1,y1)
dist=(Point.distance(Point(x2,y2)))

为:

x = Point(x1,y1)
dist = x.distance(Point(x2,y2))

说明:distance不是类方法(静态方法),因此应该在类的对象上调用它 - 而不是类本身。所以第一个调用Point(x1,y1)应该分配给一个变量(这里我使用x)然后我们将使用我们刚刚创建的这个Point对象来测量距离创建的另一个点的距离飞翔:Point(x2,y2)

我们还可以创建并保存另一个点:

x = Point(x1,y1)
y = Point(x2,y2)
dist = x.distance(y)  # and now call it with both points

答案 1 :(得分:0)

您有self作为距离的参数。因此,呼叫不会是Point.distance(x1, y2)而是point1.distance(point2)

点(x1,y1)也没有做任何事情。你需要在某处分配。与point1 = Point(x1, y1)

一样