2022
我们一起努力

python中super是什么意思

pythonsuper是一个用来调用父类的方法,主要用来解决多重继承问题的,如果直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序、重复调用等种种问题;super的语法格式为:“super(type[, object-or-type])”。

具体使用步骤:

1、首先打开python编辑器,新建一个python项目。

2、在python项目中直接使用super函数调用父类。

示例代码:

#!/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')

def bar(self,message):

super(FooChild, self).bar(message)

print ('Child bar fuction')

print (self.parent)

if __name__ == '__main__':

fooChild = FooChild()

fooChild.bar('HelloWorld')

输出结果:

Parent

Child

HelloWorld from Parent

Child bar fuction

I'm the parent.

赞(0)
文章名称:《python中super是什么意思》
文章链接:https://www.fzvps.com/91204.html
本站文章来源于互联网,如有侵权,请联系管理删除,本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
图片版权归属各自创作者所有,图片水印出于防止被无耻之徒盗取劳动成果的目的。

评论 抢沙发

评论前必须登录!