2017-04-26 49 views
-2

我需要爲Polygon類提供一個length()方法,該方法通過累加每個點到下一個點的距離來返回多邊形輪廓的總長度,包括從最後一點到第一點的距離。例如:3點多邊形poly = Poly(p1,p2,p3),poly.length()應返回從p1到p2的距離加上從p2到p3的距離加上從p3到p1的距離。 我應該如何在oop中設置length()方法? 這裏是我的代碼:如何設置方法來獲取每個點的總長度

所以我已經定義了一個DIST()方法thatreturns給定點的2D距離

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) 

感謝:

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 

,但仍然會停留在如何從每個點獲得輪廓的總長度...

+0

使用畢達哥拉斯定理來得到距離,然後把它們加起來?沒有看到你的代碼或你如何存儲多邊形的點,沒有辦法回答這個問題。 – kindall

+0

嗨,我只是更新了我的原始代碼 – Sophie

回答

0

如果您純粹尋找類和方法的結構,那麼您有幾個選項。正如你所說的,你可以使用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裝飾恢復功能,如果它是一個屬性:

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 
相關問題