2012-12-28 144 views
-2

我得到一個好點,但我仍然需要: 定義一個平等的方法來比較X和 ─如果兩個點具有相同的x和y座標另一個點的y座標,返回True。否則,返回False 用於比較另一個點的ID的身份識別方法 ─如果兩個點的ID相同,則返回True。否則,返回False 一種方法來測量從當前通過方法參數傳遞到另一個點的距離。學習OOP(類)

我只是混淆了你如何存儲第一個點與另一個點進行比較。

這是我到目前爲止有:

class Geometry(object): 

    control_id=0 
    def __init__(self): 
     self.control_id+=1 
     self.id=control_id 

class Point(object): 
    def __init__(self, x, y): 
     self.x=float(x) 
     self.y=float(y) 
    def __repr__(self): 
     return "Point object at: (%s, %s)" % (self.x, self.y) 

p1 = Point(1.216, 3.4582) 
print p1 

result: Point object at: (1.216, 3.4582) 
+1

http://learnpythonthehardway.org/book/ex42.html會是一個很好的教程通過工作,然後你可以適應你的功課。 – sean

+2

這個問題很基礎,請先通過教程。檢查此列表:http://stackoverflow.com/questions/207701/python-tutorial-for-total-beginners – XORcist

+1

你沒有提出一個實際的問題。 –

回答

1

你已經混了你的繼承和您的實例變量賦值。

嘗試一些簡單:

from math import sqrt 

class Point(object): 
    def __init__(self, y, x): 
     self.x = float(x) 
     self.y = float(y) 

    def __repr__(self): 
     return "Point object at: (%s, %s)" % (self.y, self.x) 

    def __cmp__(self, point): 
     """compare two points via ==, <, >, and so on""" 
     return cmp(self.dist_from_origin(), point.dist_from_origin()) 

    def dist_from_origin(self): 
     """Euclidean distance of a point from (0, 0)""" 
     return math.sqrt() #your work goes here... 

一旦你獲得這麼多了,嘗試移動到一個Line對象,採用兩個Point實例,並分配一個m屬性,表示斜率。然後,嘗試使用this formula爲該行實現__len__函數。

編輯:

至於你id問題去,巨蟒對每個對象它創建分配一個ID ......但是,這並不意味着是「相同」的對象具有相同的ID。

>>> a = Point(2, 2) 
>>> b = Point(2, 2) 
>>> a == b 
True 
>>> a is b 
False 
>>> id(a), id(b) 
(41217048L, 41216824L) 
>>> c = a 
>>> c is a 
True 
>>> id(a), id(c) 
(41217048L, 41217048L) 

正如你所看到的,a == b說,他們是從原點一樣的... 距離。

您可能想要創建一個方法來比較兩個Point實例的xy屬性,如果兩個點具有相同的座標,則返回True。至於id問題你有?只需使用內置的id()功能即可。

+0

這非常有幫助。當我傳遞「對象」時,它是否保留了ID(control_id),這就是爲什麼你沒有添加它?還是你忽略了包含它?現在,試圖找出比較。我想我只是做,如果point()=點():返回true ......實際上,這是沒有意義的。我仍然困惑於如何比較點和我問的其他事情。 – Jack

+0

我更新了我的答案。 – Droogans

1

像超類中的全局計數器這樣的靜態字段應該明確引用:Geometry.counter

此實現計算兩個點之間的距離爲Manhattan距離:

import operator 

class Geometry(object): 

    counter=0 

    def __init__(self): 
     super(Geometry, self).__init__() 
     Geometry.counter += 1 
     self.ID = Geometry.counter 


class Point(Geometry): 

    def __init__(self, x, y): 
     super(Point, self).__init__() 
     self.x, self.y = (float(x), float(y)) 

    def __repr__(self): 
     return "(%d, %d)" % (self.x, self.y) 

    def __eq__(self, point): 
     if type(point) is Point: 
      if self.x == point.x: 
       if self.y == point.y: 
        return True 
     return False 

    def dist(self, point): 
     if type(point) is Point: 
      return sum(map(operator.abs, map(operator.sub, 
       [self.x, self.y], [point.x, point.y]))) 
     else: 
      return None 

輸出:

>>> p=Point(2,4) 
>>> q=Point(1,5) 
>>> p.dist(q) 
2.0 
>>> p == q 
False 
>>> q.ID 
4 
>>> p 
(2, 4)