使用距离公式的两点之间的距离

时间:2017-01-03 21:26:24

标签: python wing-ide

所以我需要计算当前点和参数&中指定的另一个点之间的距离。返回计算的距离

我的print语句需要看起来像这样:

> print p1.distance(p2)   
5.0

我目前的代码:

import math

class Geometry (object):
    next_id = 0
    def __init__(self):
        self.id = Geometry.next_id
        Geometry.next_id += 1

geo1 = Geometry()
print geo1.id
geo2 = Geometry()
print geo2.id

class Point(Geometry):
    next_id = 0

    def __init__(self,x,y,):
        self.x = x
        self.y = y
        self.id = Point.next_id
        Point.next_id += 1  

    def __str__(self):
        return "(%0.2f, %0.2f)" % (self.x, self.y)

    def identify():
        if(p0.id == p1.id):
            print "True"
        else:
            print "False"

    def equality():
        if (self.x == self.y):
            print "True"
        else:
            print "False"  

    def distance(p0, p1):
        p1 = pts1
        pts1 = [(7.35,8.20)]
        p0 = pts0
        pts0 = [(5,5)]
        dist = math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
        return dist

p0 = Point(5,5)
print p0.id
p1 = Point(7.35,8.20)
print p1.id
print p1
print p0 == p1
print p0.id == p1.id

我不确定如何分离x&我的Point类中的y值,用于等式中。

3 个答案:

答案 0 :(得分:1)

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

您从未定义some_point[index]的行为,因此失败。按照保存方式访问变量。

答案 1 :(得分:0)

您应该使用p0.xp0.yp1.xp1.y。但是你不应该覆盖参数变量。

def distance(p0, p1):
    dist = math.sqrt((p0.x - p1.x)**2 + (p0.y - p1.y)**2)
    return dist

答案 2 :(得分:0)

您的distance方法应该按照自己的观点self进行操作,就像您在__str__中所做的那样)和另一点(也可以称之为p,或者像other)。

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

使用示例:

p0 = Point(2, 4)
p1 = Point(6, 1)
print(str(p0.distance(p1)))
# 5.0