温馨提示×

python中super是什么意思

摘星
458
2021-05-31 15:51:51
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

python中super是什么意思

具体使用步骤:

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.

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java中super是什么意思

0