我对python中super()机制的一点理解

对python中super()的一点理解

欢迎关注公众号【拇指笔记】,公众号刚开始办,各位csdn的大佬来波关注呗~

在类的继承里,super()解决了子类调用父类方法的一些问题。
一般说来,在子类中调用父类的方法有两种,最简单的是将对象调用转换为类调用。

class father(object):
    def out(self,message):
        print(message)

class child(father):
    def out(self,message):
        father.out(self,message)
        #这里self需要显示传递
        
child().out('super')     

从上面的例子可以看出,这样的类调在多继承时需要重复写多次;在改变父类名称时,子类可能涉及多次修改。因此引入了super()机制。

class father(object):
    def out(self,message):
        print(message)

class child(father):
    def out(self,message):
        super(child,self).out(message)
        
child().out('super') 

上例并不能看出super()机制和类调用的明显差异。但在多继承时,super()机制和类调用的差别更加明显。

#类调用
class A(object):
    def __init__(self):      
        print("enter A",end=" ")
        print("out A",end=" ")
        
class B(A):
    def __init__(self):
        print("enter B",end=" ")
        A.__init__(self)
        #类调用要显式传递self
        print("out B",end=" ")
    
class B(A):
    def __init__(self):
        print("enter B",end=" ")
        A.__init__(self)
        print("out B",end=" ")

class D(B,C):
    def __init__(self):
        print("enter D",end=" ")
        B.__init__(self)
        C.__init__(self)
        print("out D",end=" ")
        
D() 

使用super()机制

#super()机制
class A(object):
    def __init__(self):      
        print("enter A",end=" ")
        print("out A",end=" ")
        
class B(A):
    def __init__(self):
        print("enter B",end=" ")
        super(B,self).__init__()
        print("out B",end=" ")
    
class C(A):
    def __init__(self):
        print("enter C",end=" ")
        super(C,self).__init__()
        print("out C",end=" ")

class D(B,C):
    def __init__(self):
        print("enter D",end=" ")
        super(D,self).__init__()
        print("out D",end=" ")

D()

输出:

#类调用方法的输出结果
enter D enter B enter A out A out B enter C enter A out A out C out D 
#使用super()机制的输出结果
enter D enter B enter C enter A out A out C out B out D 

可以看出,在super机制下,公共父类仅被执行了一次;而在类调用方法中,公告父类被执行了

发布了31 篇原创文章 · 获赞 72 · 访问量 4953

猜你喜欢

转载自blog.csdn.net/weixin_44610644/article/details/104938720
今日推荐