Python错误:必须使用Point实例作为第一个参数调用未绑定方法distance()(获取classobj实例)

时间:2017-10-30 10:40:33

标签: python-2.7 python-3.x

执行以下代码

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self,x1,y1,x2,y2):
        d = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
        print ("Distance between the points is " + "%0.6f" % d)
        return d

def main():
    x = float(input("Enter x coordinate of first circle's centre: "))
    y = float(input("Enter y coordinate of the first circle's centre: "))
    r = float(input("Enter first circle's radius: "))
    pointx1 = x
    pointy1 = y
    first_circle = circle(x, y, r)
    print(first_circle)
    x = float(input("\nEnter x coordinate of second circle's centre: "))
    y = float(input("Enter y coordinate of the second circle's centre: "))
    r = float(input("Enter second circle's radius: "))
    pointx2 = x
    pointy2 = y
    second_circle = circle(x, y, r)
    Point.distance(Point,pointx1, pointy1, pointx2, pointy2)

我收到以下错误:

File "C:/Users/Deepak/PycharmProjects/Submission/Shapes.py",line 102,in main 
Point.distance(Point,pointx1, pointy1, pointx2, pointy2)
TypeError: unbound method distance() must be called with Point instance as 
first argument (got classobj instance instead)

我正在尝试从用户读取中心坐标和两个圆的半径,然后我试图确定它们的中心之间的距离。我尝试只发送四个参数到Point.distance()但是也返回了一个错误。请帮忙。我该怎么做才能解决这个错误。

1 个答案:

答案 0 :(得分:1)

我不确定你错了我认为你可能错了,但是你没有通过self的论证,你只通过pointx1, pointy1, pointx2, pointy2self被处理了内部。实际上你的距离函数并没有真正利用类结构。您可能会想到,例如:

from math import sqrt

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


    @classmethod
    def two_point_distance(cls, pnt1, pnt2):
        return sqrt( ( pnt1.x - pnt2.x )**2 + ( pnt1.y - pnt2.y )**2 )


    def distance_to(self, pnt2):
        return sqrt( ( self.x - pnt2.x )**2 + ( self.y - pnt2.y )**2 )


pntA=Point(3, 2)
pntB=Point(7, 8)

print Point.two_point_distance( pntA, pntB )
print pntA.distance_to( pntB )