association.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. 对象之间的关联关系
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-12
  6. """
  7. from math import sqrt
  8. class Point(object):
  9. def __init__(self, x=0, y=0):
  10. self._x = x
  11. self._y = y
  12. def move_to(self, x, y):
  13. self._x = x
  14. self._y = y
  15. def move_by(self, dx, dy):
  16. self._x += dx
  17. self._y += dy
  18. def distance_to(self, other):
  19. dx = self._x - other._x
  20. dy = self._y - other._y
  21. return sqrt(dx ** 2 + dy ** 2)
  22. def __str__(self):
  23. return '(%s, %s)' % (str(self._x), str(self._y))
  24. class Line(object):
  25. def __init__(self, start=Point(0, 0), end=Point(0, 0)):
  26. self._start = start
  27. self._end = end
  28. @property
  29. def start(self):
  30. return self._start
  31. @start.setter
  32. def start(self, start):
  33. self._start = start
  34. @property
  35. def end(self):
  36. return self.end
  37. @end.setter
  38. def end(self, end):
  39. self._end = end
  40. @property
  41. def length(self):
  42. return self._start.distance_to(self._end)
  43. if __name__ == '__main__':
  44. p1 = Point(3, 5)
  45. print(p1)
  46. p2 = Point(-2, -1.5)
  47. print(p2)
  48. line = Line(p1, p2)
  49. print(line.length)
  50. line.start.move_to(2, 1)
  51. line.end = Point(1, 2)
  52. print(line.length)