python中super的理解

以前对于继承的了解只限于java里简单的单继承,用了python后看到可以多继承,看到super非常懵逼,现在来记录一下super的用法
在类的继承里面super()非常常用,它解决了子类调用父类方法的一些问题,父类多次被调用时只执行一次,优化了执行逻辑
在执行子类的super时,实际上执行的是父类中的同名方法
一般super写为:
python2中 super(当前类名,self).函数名()
python3中 super().函数名()

class A():
    def go(self):
        print ("go A go!")
    def stop(self):
        print ("stop A stop!")
    def pause(self):
        raise Exception("Not Implemented")
class B(A):
    def go(self):
        super(B, self).go()
        print ("go B go!")
class C(A):
    def go(self):
        super(C, self).go()
        print ("go C go!")
    def stop(self):
        super(C, self).stop()
        print ("stop C stop!")
class D(B,C):
    def go(self):
        super(D, self).go()
        print ("go D go!")
    def stop(self):
        super(D, self).stop()
        print ("stop D stop!")
    def pause(self):
        print ("wait D wait!")
class E(B,C):
    pass
a = A()
b = B()
c = C()
d = D()
e = E()
# 说明下列代码的输出结果
a.go()
print('--------')
b.go()
print('--------')
c.go()
print('--------')
d.go()
print('--------')
e.go()
print('--------')
a.stop()
print('--------')
b.stop()
print('--------')
c.stop()
print('--------')
d.stop()
print('--------')
e.stop()
print(D.mro())
a.pause()
b.pause()
c.pause()
d.pause()
e.pause()

输出结果是

a.go()# go A go!
b.go()# go A go!# go B go!
c.go()# go A go!# go C go!
d.go()# go A go!# go C go!# go B go!# go D go!
e.go()# go A go!# go C go!# go B go!
a.stop()# stop A stop!
b.stop()# stop A stop!
c.stop()# stop A stop!# stop C stop!
d.stop()# stop A stop!# stop C stop!# stop D stop!
e.stop()# stop A stop!
a.pause()# ... Exception: Not Implemented
b.pause()# ... Exception: Not Implemented
c.pause()# ... Exception: Not Implemented
d.pause()# wait D wait!
e.pause()# ...Exception: Not Implemented

以下对于super说明几点:
继承的功能:父类的代码重用

super实现原理:通过c3算法,生成mro(method resolution order)列表,根据列表中元素顺序查询调用
新式类调用顺序为广度优先,旧式类为深度优先(注:Python 2.x中默认都是经典类,只有显式继承了object才是新式类,Python 3.x中默认都是新式类,不必显式的继承object

Python 3.x中默认都是新式类,不必显式的继承object
super类似于嵌套的一种设计,当代码执行到super实例化后,先去找同级父类,若没有其余父类,再执行自身父类,再往下走,简洁点的三个原则就是:子类在父类前,所有类不重复调用,从左到右

用一个例子说明子类在父类前,且是广度优先

class A:
  def __init__(self):
    print("Enter A")
    print("Leave A")
class B(A):
  def __init__(self):
    print("Enter B")
    super(B, self).__init__()
    print("Leave B")
class C(A):
  def __init__(self):
    print("Enter C")
    super(C, self).__init__()
    print("Leave C")
class D(A):
  def __init__(self):
    print("Enter D")
    super(D, self).__init__()
    print("Leave D")
class E(B, C, D):
  def __init__(self):
    print("Enter E")
    super(E, self).__init__()
    print("Leave E")
E()

执行结果为

Enter E
Enter B
Enter C
Enter D
Enter A
Leave A
Leave D
Leave C
Leave B
Leave E

在输出Enter E后输出的是Enter B C D 之后才是Enter A

猜你喜欢

转载自blog.csdn.net/weixin_38267508/article/details/87859268
今日推荐