forked from jackfrued/Python-100-Days
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shape.py
66 lines (44 loc) · 1010 Bytes
/
shape.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
继承的应用
- 抽象类
- 抽象方法
- 方法重写
- 多态
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from abc import ABCMeta, abstractmethod
from math import pi
class Shape(object, metaclass=ABCMeta):
@abstractmethod
def perimeter(self):
pass
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self._radius = radius
def perimeter(self):
return 2 * pi * self._radius
def area(self):
return pi * self._radius ** 2
def __str__(self):
return '我是一个圆'
class Rect(Shape):
def __init__(self, width, height):
self._width = width
self._height = height
def perimeter(self):
return 2 * (self._width + self._height)
def area(self):
return self._width * self._height
def __str__(self):
return '我是一个矩形'
if __name__ == '__main__':
shapes = [Circle(5), Circle(3.2), Rect(3.2, 6.3)]
for shape in shapes:
print(shape)
print('周长:', shape.perimeter())
print('面积:', shape.area())