2012-04-13 17 views
-1

クラスメソッドに問題があります。私は持っているすべての情報を投稿します。私は与えられた質問に関連する方法を書く必要があります。クラスメソッドの問題 - Python

import math 
epsilon = 0.000001 
class Point(object): 
    def __init__(self, x, y): 
     self._x = x 
     self._y = y 

    def __repr__(self): 
     return "Point({0}, {1})".format(self._x, self._y) 

最初の質問; disttopointというメソッドを追加する必要があります。このメソッドは、引数として別のポイントオブジェクトpをとり、2つのポイント間のユークリッド距離を返します。私はmath.sqrtを使うことができます。

テストケース:

abc = Point(1,2) 
efg = Point(3,4) 
abc.disttopoint(efg) ===> 2.8284271 

2番目の質問。別のポイントオブジェクトpを引数とするisnearというメソッドを追加し、このポイントとpの間の距離がε(上記のクラススケルトンで定義されている)未満であればTrueを返し、それ以外の場合はFalseを返します。 disttopointを使用してください。

テストケース:

abc = Point(1,2) 
efg = Point(1.00000000001, 2.0000000001) 
abc.isnear(efg) ===> True 

3番目の質問。 addpointというメソッドを追加します。addpointは、別のポイントオブジェクトpを引数としてとり、このポイントをointの古い値とpの値の合計になるように変更します。

テストケース;

abc = Point(1,2) 
efg = Point(3,4) 
abc.add_point(bar) 
repr(abc) ==> "Point(4,6) 
+1

どうすればいいですか? –

+0

あなたはいくつかのPythonの魔法を追加することができます: 'add_point'(またはそれと同様の)メソッドを持つ代わりに' __iadd__'を使うことができます。 'abc + = bar'を実行します。必要に応じて他の演算子についても繰り返します(すべてのドキュメントについては、ドキュメントを参照してください) –

答えて

0
class Point(object): 
    # __init__ and __repr__ methods 
    # ... 
    def disttopoint(self, other): 
     # do something using self and other to calculate distance to point 
     # result = distance to point 
     return result 

    def isnear(self, other): 
     if (self.disttopoint(other) < epsilon): 
      return True 
     return False 
+0

最後のものは何でしょうか?私は最初の2つを知ることができると思うが、私が知りませんが最後のものは – Hoops

+0

@Hoops isnearまたはadd_pointを意味しますか?ジョーディは基本的にadd_pointを行う方法を示しています –

+0

woops mean isnear – Hoops

0

あなたの問題は何ですか?

あなたは方法を作成することに固執していますか?

Class Point(object): 
    # make it part of the class as it will be used in it 
    # and not in the module 
    epsilon = 0.000001 

    def __init__(self, x, y): 
     self._x = x 
     self._y = y 

    def __repr__(self): 
     return "Point({0}, {1})".format(self._x, self._y) 

    def add_point(self, point): 
     """ Sum the point values to the instance. """ 
     self._x += point._x 
     self._y += point._y 

    def dist_to_point(self, point): 
     """ returns the euclidean distance between the instance and the point.""" 
     return math.sqrt(blablab) 

    def is_near(self, point): 
     """ returns True if the distance between this point and p is less than epsilon.""" 
     return self.dist_to_point(point) < self.epsilon 

これは役立ちますか?

ジョルディ

+0

実際にどのようにまとめて結びつけるのかというと、ちょうど混乱しています。最初の2つは私が持っていると思う、最後のものはあまりありません – Hoops

0
def dist_to_point(self, point): 
     """ returns the euclidean distance between the instance and the point.""" 
     return math.sqrt(res) 

変数 "RES" は何が含まれている必要がありますか?

乾杯