python2的经典类、新式类与python3中的新式类
- 经典类
- 新式类
- 新式类
python2
如果是python2环境,pycharm最开始需要写上 coding:utf-8
class D: pass # def func(self): # print('d') class B(D): pass # def func(self): # print('b') class C(D): pass def func(self): print('c') class A(B,C): pass def func(self): print('a') a = A() a.func()
执行顺序:
a
b
d
c
python2.x中的经典类
多继承中深度优先
没有mro提示你顺序
没有super
总结:
python2.x版本中存在两种类
- 经典类
- 不主动继承object类的所有类都是经典类
- 继承关系遵循深度优先算法
- 没有mro,没有super
- 新式类
- 所有继承object类的都是新式类
- 和py3一样继承遵循mro顺序和c3算法
- 有mro方法,但是super的使用必须传参数super(子类名,对象名).方法名
python3
新式类 : 默认继承object类 # object 是所有类的父类
- 在python3中 所有的类都是新式类,所有的新式类的继承顺序都遵循C3算法,也叫广度优先算法
- 可以使用类名.__mro__这个方法来查看这个继承顺序
class A: pass def func(self):print('A') class B(A): pass def func(self):print('B') class C(A): pass def func(self):print('C') class D(B): pass def func(self):print('D') class E(C): pass def func(self):print('E') class F(D,E): pass def func(self):print('F') f= F() f.func()
利用C3算法推上面继承顺序
L(A) = [A] + [O] A = [O] L[A] = AO # 单纯的A类的继承顺序 L(B) = [B] + [AO] B = [AO] BA = [O] L(B) = BAO L(C) = [C] + [AO] C = [AO] CA = [O] L(C) = CAO L(D) = [D] + [BAO] D = [BAO] DB = [AO] DBA = [O] L(D) = DBAO L(E) = [E] + [CAO] E = [CAO] EC = [AO] ECA = [O] L(E) = ECAO L(F) = [F] + [DBAO] + [ECAO] F = [DBAO] + [ECAO] FD = [BAO] + [ECAO] FDB = [AO] + [ECAO] FDBE = [AO] + [CAO] FDBEC = [AO] + [AO] FDBECA = [O] + [O] L(F) = FDBECAO
以上还可以使用 类名.__mro__
print(F.__mro__)
执行结果:
(<class '__main__.F'>,
<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.E'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>)
总结:
python3.x中的类和py2.x中的新式类有什么区别???
- 不需要主动继承object
- py3中super()可以直接用,py2中使用必须传参数super(子类名,对象名).方法名
surper在多继承中的意义
class A: def func(self):print('A') class B(A): def func(self): super().func() print('B') class C(A): def func(self): super().func() print('C') class D(B,C): def func(self): super().func() print('D')d = D()d.func()
执行顺序:
A
C
B
D