diff --git a/geometry.py b/geometry.py index d3219b1..b63cef3 100644 --- a/geometry.py +++ b/geometry.py @@ -2,6 +2,53 @@ # -*- coding: utf-8 -*- +class BaseGeometry(object): + """ + Base geometry class sharing methods to child classes. + """ + + def __init__(self, coordinates: list): + self.coordinates = coordinates + + @property + def coordinates(self) -> list: + """ + Property getter for coordinates. Can be overwritten by child classes. + """ + return self._coordinates if not None else list() + + @coordinates.setter + def coordinates(self, coordinates: list): + """ + Property setter for coordinates. Should be overwritten from child classes. + """ + self._coordinates = coordinates + + @coordinates.deleter + def coordinates(self): + self._coordinates = [] + + @property + def envelope(self) -> list: + """ + Return the envelope or bounding box of the geometry. + """ + min_x = float('inf') + min_y = float('inf') + max_x = float('-inf') + max_y = float('-inf') + for coordinate in self.coordinates: + if coordinate[0] < min_x: + min_x = coordinate[0] + if coordinate[1] < min_y: + min_y = coordinate[1] + if coordinate[0] > max_x: + max_x = coordinate[0] + if coordinate[1] > max_y: + max_y = coordinate[1] + return [min_x, max_x, min_y, max_y] + + class MyPolygon: def __init__(self, coordinates): diff --git a/tests/test_geometry.py b/tests/test_geometry.py index 8ff0df6..ffe9b2f 100644 --- a/tests/test_geometry.py +++ b/tests/test_geometry.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- -from geometry import MyPolygon +from geometry import MyPolygon, BaseGeometry def test_coordinates(): @@ -15,4 +15,17 @@ def test_coordinates(): def test_envelope(): - assert False + coordinates = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)] + base_geometry: BaseGeometry = BaseGeometry(coordinates=coordinates) + assert [1, 2, 1, 2] == base_geometry.envelope + + +def test_coordinates_setter_getter_deleter(): + coordinates1 = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)] + coordinates2 = [(1, 2), (1, 2), (2, 2), (2, 1), (1, 4)] + base_geometry: BaseGeometry = BaseGeometry(coordinates=coordinates1) + assert base_geometry.coordinates == coordinates1 + base_geometry.coordinates = coordinates2 + assert base_geometry.coordinates == coordinates2 + del base_geometry.coordinates + assert base_geometry.coordinates == []