码迷,mamicode.com
首页 > 编程语言 > 详细

Python第十七天 抽象类

时间:2018-08-28 21:17:39      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:rom   typeerror   abs   实现   with   test   查找   color   err   

 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>]

 

Python第十七天 抽象类

标签:rom   typeerror   abs   实现   with   test   查找   color   err   

原文地址:https://www.cnblogs.com/golzn2018/p/9550582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!