Python 如何设置方法以获取每个点的总长度

Python 如何设置方法以获取每个点的总长度,python,oop,Python,Oop,我需要为Polygon类提供一个length方法,该方法通过汇总从每个点到下一点的距离(包括从最后一点到第一点的距离)来返回多边形轮廓的总长度。例如:3点多边形多边形=多边形1,p2,p3,多边形长度应返回p1到p2的距离加上p2到p3的距离加上p3到p1的距离。 我应该如何在oop中设置长度方法? 这是我的密码: class Polygon: def __init__(self, points=[]): # init with list of points print("creatin

我需要为Polygon类提供一个length方法,该方法通过汇总从每个点到下一点的距离(包括从最后一点到第一点的距离)来返回多边形轮廓的总长度。例如:3点多边形多边形=多边形1,p2,p3,多边形长度应返回p1到p2的距离加上p2到p3的距离加上p3到p1的距离。 我应该如何在oop中设置长度方法? 这是我的密码:

class Polygon:
def __init__(self, points=[]): # init with list of points
    print("creating an instance of class", self.__class__.__name__)
    self.point_list = points[:]  # list to store a sequence of points

def draw(self):
    turtle.penup()
    for p in self.point_list:
        p.draw()
        turtle.pendown()
    # go back to first point to close the polygon
    self.point_list[0].draw()

def num_points(self):
    return len(point_list)
谢谢

所以我已经定义了一个dist方法,它返回到给定点的2D距离:

def dist(self, other):
    dis_x = (other.x - self.x)*(other.x - self.x) 
    dis_y = (other.y - self.y)*(other.y - self.y)
    dis_new = math.sqrt(dis_x + dis_y)
    return dis_new

但是仍然会被困在如何从每个点获得轮廓的总长度上…

如果您纯粹是在寻找类和方法的结构,那么您有一些选择。您可以使用前面提到的Poly类的length方法,也可以使用在其下运行函数的动态属性

使用您的提案:

class Poly(object):
    def __init__(self, *args):
        for arg in args:
            # Do something with each side
            print(arg)

    def length(self):
        return get_length_of_perimeter()
您可以这样称呼它:

poly = Poly(p1, p2, p3)
print(poly.length())
或者,您可以使用@property decorator将函数作为属性返回:

class Poly(object):
    def __init__(self, *args):
        for arg in args:
            # Do something with each side
            print(arg)

    @property
    def length(self):
        return get_length_of_perimeter()
然后你会这样称呼它:

poly = Poly(p1, p2, p3)
print(poly.length)  # notice you're not calling length as if it was a method

用毕达哥拉斯定理得到距离,然后把它们加起来?如果看不到你的代码或你是如何存储poliygon的积分,就没有办法回答这个问题。嗨,我刚刚更新了我的原始代码