Python-100-Days/Day01-15/code/Day09/shape.py

65 lines
1.1 KiB
Python
Raw Normal View History

2018-04-27 00:00:22 +08:00
"""
继承的应用
2019-05-03 21:17:36 +08:00
- 抽象类
- 抽象方法
- 方法重写
- 多态
2018-04-27 00:00:22 +08:00
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from abc import ABCMeta, abstractmethod
from math import pi
class Shape(object, metaclass=ABCMeta):
2019-05-03 21:17:36 +08:00
@abstractmethod
def perimeter(self):
pass
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
@abstractmethod
def area(self):
pass
2018-04-27 00:00:22 +08:00
class Circle(Shape):
2019-05-03 21:17:36 +08:00
def __init__(self, radius):
self._radius = radius
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def perimeter(self):
return 2 * pi * self._radius
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def area(self):
return pi * self._radius ** 2
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def __str__(self):
return '我是一个圆'
2018-04-27 00:00:22 +08:00
class Rect(Shape):
2019-05-03 21:17:36 +08:00
def __init__(self, width, height):
self._width = width
self._height = height
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def perimeter(self):
return 2 * (self._width + self._height)
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def area(self):
return self._width * self._height
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def __str__(self):
return '我是一个矩形'
2018-04-27 00:00:22 +08:00
if __name__ == '__main__':
2019-05-03 21:17:36 +08:00
shapes = [Circle(5), Circle(3.2), Rect(3.2, 6.3)]
for shape in shapes:
print(shape)
print('周长:', shape.perimeter())
print('面积:', shape.area())