2017-04-26 7 views
-2

ポリゴンのアウトラインの長さを返すポリゴンクラスのlength()メソッドを提供する必要があります。これは、各ポイントから次のポイントまでの距離を合計します最後の点から最初の点までの距離。例:3点ポリゴンポリ=ポリ(p1、p2、p3)、poly.length()は、p1からp2までの距離にp2からp3までの距離とp3からp1までの距離を戻す必要があります。 oopでlength()メソッドを設定する方法は?まだ各ポイントの合計長さを取得する方法を設定する方法

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 

だけにどのように立ち往生:私はすでにDIST()メソッドは、指定された点までの2D距離をthatreturns定義さ

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) 

ありがとう: はここに私のコードです各点からのアウトラインの合計長さを取得します。

+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