Python第十七天 抽象类

 1 from abc import ABCMeta, abstractmethod
 2 
 3 class A(metaclass=ABCMeta):  称 A 为抽象类
 4     @abstractmethod
 5     def test(self):pass      test 为抽象方法, 必须由继承的子类实现具体功能
 6 
 7 
 8 class B(A):
 9     pass
10 
11 B()   只要创建类  B 的 对象, 就会报错

TypeError: Can't instantiate abstract class B with abstract methods test

python3,以后,新式类, 多继承,方法的查找顺序,  广度优先算法

 1 class A:
 2     def test(self):
 3         print('in A')
 4 
 5 class B(A):
 6     def test(self):
 7         print('in B')
 8         super().test()
 9 
10 class C(A):
11     def test(self):
12         print('in C')
13         super().test()
14 
15 class D(B):
16     def test(self):
17         print('in D')
18         super().test()
19 
20 class E(C):
21     def test(self):
22         print('in E')
23         super().test()
24 
25 class F(D, E):
26     def test(self):
27         print('in F')
28         super().test()
29 
30 
31 F().test()
32 
33 print(F.mro())

 执行结果

in F
in D
in B
in E
in C
in A
[<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
原文地址:https://www.cnblogs.com/golzn2018/p/9550582.html