2013-05-29 102 views
1

我是一名Python初學者,因爲我可能在我以前的問題中已經陳述過了,而且我一直在提及的一些主題沒有給出深入的解釋,因此我需要低估材料,所以我有一個問題。問題是「向方法Point添加方法距離()」,它將另一個Point對象作爲輸入並返回到該點的距離(從調用該方法的點開始)定義Python類

它在尋找什麼當這是所有輸入到模塊

>>> c = Point() 
>>> c.setx(0) 
>>> c.sety(1) 
>>> d = Point() 
>>> d.setx(1) 
>>> d.sety(0) 
>>> c.distance(d) 
1.4142135623730951 

在這裏,下面的結果我有什麼:

class Point: 
    def setx(self, xcoord): 
     self.x = xcoord 
    def sety(self, ycoord): 
     self.y = ycoord 
    def get(self): 
     return(self.x, self.y) 
    def move(self, dx, dy): 
     self.x += dx 
     self.y += dy 

然後我不知道我是否需要什麼樣的方式來定義距離謝謝你。

我有一個清晰的基線,我很確定我會開始這個,但是當談到定義距離時,我非常困惑。

+6

請不要在Python中使用getters和setter。只需直接訪問實例變量,或者對非平凡的實例變量使用[properties](http://docs.python.org/2/library/functions.html#property)。 – Cairnarvon

回答

3

都需要這樣的

def distance(self, other): 
    dist = math.hypot(self.x - other.x, self.y - other.y) 
    return dist 

的方法還需要import math在程序開始

旁白:這不是Python的在所有有你setxsety方法。你應該直接分配給屬性。例如c.x = 0

 
Help on built-in function hypot in module math: 

hypot(...) 
    hypot(x, y) 

    Return the Euclidean distance, sqrt(x*x + y*y). 
0

這是一個沒有設置和獲取的例子。 __init__是可選的。我加了__call__而不是get

class Point: 
    def __init__(self, *terms): 
     self.x = 0 
     self.y = 0 
    def __call__(self): 
     return(self.x, self.y) 
    def move(self, dx, dy): 
     self.x += dx 
     self.y += dy 
    def distance(self, other): 
     dist = math.hypot(self.x - other.x, self.y - other.y) 
     return dist 

>>> c = Point() 
>>> c.x = 0 
>>> c.y = 1 
>>> d = Point() 
>>> d.x = 1 
>>> d.y = 0 
>>> c() 
(1, 0) 
>>> c.distance(d) 
1.4142135623730951