shape.py 1010 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. 继承的应用
  3. - 抽象类
  4. - 抽象方法
  5. - 方法重写
  6. - 多态
  7. Version: 0.1
  8. Author: 骆昊
  9. Date: 2018-03-12
  10. """
  11. from abc import ABCMeta, abstractmethod
  12. from math import pi
  13. class Shape(object, metaclass=ABCMeta):
  14. @abstractmethod
  15. def perimeter(self):
  16. pass
  17. @abstractmethod
  18. def area(self):
  19. pass
  20. class Circle(Shape):
  21. def __init__(self, radius):
  22. self._radius = radius
  23. def perimeter(self):
  24. return 2 * pi * self._radius
  25. def area(self):
  26. return pi * self._radius ** 2
  27. def __str__(self):
  28. return '我是一个圆'
  29. class Rect(Shape):
  30. def __init__(self, width, height):
  31. self._width = width
  32. self._height = height
  33. def perimeter(self):
  34. return 2 * (self._width + self._height)
  35. def area(self):
  36. return self._width * self._height
  37. def __str__(self):
  38. return '我是一个矩形'
  39. if __name__ == '__main__':
  40. shapes = [Circle(5), Circle(3.2), Rect(3.2, 6.3)]
  41. for shape in shapes:
  42. print(shape)
  43. print('周长:', shape.perimeter())
  44. print('面积:', shape.area())