2014-11-23 19 views
0

我需要能夠移動點並檢查特定的點值。這是代碼:移動點並檢查特定的起始值,使用類python

class Point(object): 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 
    def move(self) 
     #Here I want to move my points 

下一個類是一個線串。它必須能夠處理X設定點

class LineString(Point): 
    def __init__(self, *points): 
     self.points = [] 
     for point in points: 
      if not isinstance(point, Point): 
       point = Point(*point) 
      self.points.append(point) 
    def __getitem__(self): 
     #Here I want to inspect the value of the specific 
     # e.g. y value for the start point after it has been moved 

的我有點不確定如何獲得__getitem__工作,無論是在正確的位置。是否應該在class Point之下?這可以以另一種方式完成嗎?

已編輯的代碼;

from numpy import sqrt 
import math 

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

    def dist(self, point): 
     return math.hypot(self.x - point.x, self.y - point.y) 

    def move(self, dx, dy): 
     self.x = self.x + dx 
     self.y = self.y + dy 

class LineString(Point): 
    def __init__(self, *points): 
     self.points = [] 
     for point in points: 
      if not isinstance(point, Point): 
       point = Point(*point) 
      self.points.append(point) 

    def length(self): 
     return sum(p1.dist(p2) for p1, p2 in zip(self.points[1:], self.points[:-1])) 

    def move (self, x, y): 
     for p in self.points: 
      p.move(x, y) 

    def __getitem__(self, key): 
     return self.points[key] 
+0

目前尚不清楚你需要什麼'__getitem'做。你能否用清晰的英文解釋你想要的代碼? – 2014-11-23 22:57:12

+0

是的。我希望程序的用戶能夠移動插入點並檢查新值。例如,如果我們有lin = LineString((2,2),(3,3))的線串。我想能夠使用lin.move(1,1),它將移動LineString在x,y中移動1步。那麼應該有可能返回新值。這樣的屁股lin [0] .y == 3將是真實的。 – 2014-11-24 09:58:08

回答

0

我想這大概是你想要什麼:

你似乎並不真正需要的字典(爲一條線,我覺得一個列表更有意義呢)。所以Line類只是一個Point s的列表,它提供了一個move_all_points函數來將它們全部轉換。由於Line子類的列表,你會得到列出的所有標準的行爲自由:

class Point(object): 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 
    def __repr__(self): 
     return "<Point({},{})>".format(self.x, self.y) 
    def __str__(self): 
     return(repr(self)) 
    def move(self, dx, dy): 
     """Move the point by (dx, dy).""" 
     self.x += dx 
     self.y += dy 

class Line(list): 
    """A list of points that make up a line.""" 
    def move_all_points(self, dx, dy): 
     for p in self: 
      p.move(dx, dy) 

,那麼你可以按如下方式使用它們:

>>> p1, p2, p3 = Point(0, 0), Point(5, 0), Point(10, 10) 

>>> my_line = Line((p1, p2,)) 
>>> print my_line 
[<Point(0,0)>, <Point(5,0)>] 

>>> my_line.append(p3) 
>>> print my_line 
[<Point(0,0)>, <Point(5,0)>, <Point(10,10)>] 

>>> p4 = Point(100,100) 
>>> my_line.move_all_points(1, 1) 
>>> print my_line 
[<Point(1,1)>, <Point(6,1)>, <Point(11,11)>] 

>>> my_line.append(p4) 
>>> print my_line 
[<Point(1,1)>, <Point(6,1)>, <Point(11,11)>, <Point(100,100)>] 
+0

感謝您提供建議的代碼。然而,它並沒有做到我想要的,很可能是因爲我對此不清楚。我將發佈我的完成代碼。 – 2014-12-01 20:03:09

相關問題