Python super()函数

super()函数是用于调用父类(超类)的一个方法

super()是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO),重复调用(钻石继承)等种种问题。

MRO是类的方法解析顺序表,其实也就是继承父类方法时的顺序表

语法:

super(type, object-or-type])

type 类

object-or-type 类,一般是self

例子1:

class A():
    def add(self, num):
        print(num + 1)
    
class B(A):
    def test(self, x):
        super().add(x)

obj = B()
obj.add(4)

执行结果: 5

例子2:

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        self.parent = 'test' #如果self.parent 在super的下面的话,则会覆盖掉父类的self.parent, 取最新的
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild,self).__init__()  #在这里相当于是调用了父类里面init所有的方法 
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

执行结果:

例子3:

class GrandParent():
    def __init__(self):
        self.name = 'alex'
        self.grandparent = 'I am grandparent'
        self.address = '浙江'
        print('I am alex')
    
    def action(self, thing):
        print('%s like %s'%(self.name, thing))
    

class Parent(GrandParent):
    def __init__(self):
        self.parent = 'I am parent'
        self.address = '上海'
        super(Parent, self).__init__()
        self.name = 'aun'
        print('I am aun')
    
    def action(self, thing):
        print('%s like %s'%(self.name, thing))
    
    def get_name(self):
        return self.name
    
class Me(Parent):
    def __init__(self):
        self.name = 'me'
        super(Me, self).__init__()#放在下面会覆盖掉self.name
        print('I am me')
    
    def action(self, thing):
        #最终找到的是父类的父类的name,一直被覆盖
        super(Me, self).action(thing)
        print('my GrandParent name is %s'%(super(Me, self).get_name()))
        print(self.address)#可以一直往上找父类方法
 
Me().action('apple')

执行结果

 

posted @ 2020-12-17 01:54  风不再来  阅读(110)  评论(0编辑  收藏  举报