2014-01-19 3 views
0

선 스트링을 나타내는 클래스를 구현하고 싶습니다. 나는 "Point"라는 클래스를 가지고 있는데, 은 2 개의 좌표가있는 점을 나타내며이 점을 내부 정점을 저장하는 데 사용하고자합니다. 선 스트링입니다. 나는이 코드 조각 해낸 :포인트 클래스를 사용하여 선 스트링을 표현하는 방법

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

class LineString(Point): 
    def __init__(self, point): 
     self.point = point 

하지만 내가 좋아하는 선 스트링 지원 선 스트링 에 여러 지점을 표시하는 방법을 모른다 :

lin = LineString((1, 1), (0, 2), (3,6)) 

모르겠다을 선 스트링에 나타날 수있는 점 수. 새로운 코드 :

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

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

    def length(self): 
     L = len(self.points) 
     return L 




if __name__ == '__main__': 
    # Tests for LineString 
    # =================================== 
    lin1 = LineString((1, 1), (0, 2)) 
    assert len(lin1.points) == sqrt(2.0) 

답변

1

*argumentname와 생성자 가변 인수를 보내기 필요에 따라이 Point() 인스턴스에 튜플을 변환 할 수 있습니다

class LineString(Point): 
    def __init__(self, *points): 
     self.points = points 

:

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) 

를 두 경우 모두 self.points에서 이제 Python list 개체입니다. Point(*point) 호출에서 미러 구문을 사용합니다. point 튜플의 요소는 Point.__init__() 메서드에 대해 별도의 인수로 적용되고 에 대해 두 개의 인수로 (1, 1) 튜플을 전달합니다.

lin = LineString((1, 1), (0, 2), (3,6)) 

또는

데모 :

>>> lin = LineString((1, 1), (0, 2), (3,6)) 
>>> len(lin.points) 
3 
>>> lin.points[0] 
<__main__.Point object at 0x108988fd0> 
>>> lin.points[0].x, lin.points[0].y 
(1, 1) 
+0

감사합니다. 그러나 예를 들어 선 스트링의 길이를 어떻게 추출 할 수 있습니까? –

+1

@ f.ashouri :'len (self.points)'; 그것은 단지리스트 객체 일 뿐이다. –

+0

나를 위해 그것은 오류를 throw합니다 : LineString '객체의 속성이 없습니다'points ' –

1

라인이 포인트하지 않으며, 어느 쪽도 라인의 문자열

이제 당신도 함께 선 스트링을 구축 할 수 있습니다 . Liskov Substitution Principle은 부모 클래스 중 하나에 대해 파생 클래스의 인스턴스를 항상 대체 할 수 있어야한다고 명시합니다. 다음 코드를 고려하십시오.

def move_point(point, xdist, ydist): 
    return Point(point.x + xdist, point.y + ydist) 

p = Point(3, 4) 
q = move_point(p, 5, 6) 
assert q.x == 8 and q.y == 10 

r = LineString((2, 3), (5, 4), (8, 6)) 
s = move_point(r, 5, 6) # ??? 

무엇이 s 일 수 있습니까? 선의 문자열 (x, y) 좌표는 어떻게됩니까?

이 문제에 대한 해결책은 단순히 Point에서 LineString을 파생시키지 않는 것입니다. 대신, 코드는 다음과 같이 보일 것이다 :

def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    ... # see implementation details @ http://docs.python.org/2.7/library/itertools.html#recipes 

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

def distance(point1, point2): 
    ... # needs implementing 

class Line(object): 
    def __init__(self, a, b): # a and b must be Points 
     self.a = a 
     self.b = b 

    @property 
    def length(self): 
     return distance(self.a, self.b) 

class LineString(object): 
    def __init(self, *points): 
     # We assume that points consists only of proper Point instances. 
     # If people pass invalid arguments, it's their problem. 
     self.points = points 

    @property 
    def length(self): 
     return sum(distance(p1, p2) for p1, p2 in pairwise(self.points)) 

if __name__ == '__main__': 
    lin1 = LineString((1, 1), (0, 2)) 
    assert lin1.length == sqrt(2.0) 

또한, 부동 소수점 연산은 때때로 이상한 결과를 얻게

에 대한 설명
>>> .1 + .2 == .3 
False 
>>> .1 + .2 
0.30000000000000004 

, http://floating-point-gui.de를 참조하십시오.

관련 문제