CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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