zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python使用技巧(二十):super()方法

Python方法 技巧 Super 二十 使用
2023-09-14 09:15:32 时间

描述

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

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

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

语法

以下是 super() 方法的语法:

super(type[, object-or-type])

测试代码1:super().add(x) #等价于super().add(x) => y = x+1 print(y)

在这里插入图片描述

测试代码2: super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象

FooChild(FooParent)等价于FooParent(object)就可进行调用。
这里调用了父类参数FooParent中的方法,只需使用时将self换成输入参数即可。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
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):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild,self).__init__()    
        print ('Child')
      
    #同时调用上下bar和bars
    def bars(self,message):
        super(FooChild, self).bar(message) #这里调用了父类参数FooParent中的方法,只需使用时将self换成输入参数即可
        print ('Child bar fuction')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()  #输出的是两个初始化参数
    fooChild.bars('HelloWorld')
#     fooChild2 = FooChild('HelloWorld2')  #如何给参数
    

结果:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

参考学习来自:https://www.runoob.com/python/python-func-super.html