Python 继承实现的原理

继承顺序

Python3 :
新式类的查找顺序:广度优先

新式类的继承:
        class A(object):  Python2 3 都是了

MRO算法--生成一个列表保存继承顺序表

不找到底部

Python2 中有新式类 和 经典类
Python2 默认的是经典类

   经典类的继承是 深度优先

找到最深的,然后从头开始找

例子

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
class A(object): #定义新式类
def test(self):
print('frome A')
class B(A):
def test(self):
print('frome B')
class C(A):
def test(self):
print('frome C')
class D(B):
def test(self):
print('frome D')
class E(C):
def test(self):
print('frome E')
class F(D,E):
def test(self):
print('frome F')
f1=F()
f1.test()
print(F.__mro__)

结果:
(, , , , , , )

© 2018 Peter's Blog Center All Rights Reserved.
Theme by hiero