python中 super()函数如何使用

 时间:2026-04-26 20:21:37

1、python 3.x版本的实现:super().父类方法

class A(object):

    def show(self,x):

        print('A class: {}'.format(x+1))

class B(A):

    def show1(self,x):

        super().show(x)

        print("B class: {}".format(x))

b=B()

b.show1(1)

python中 super()函数如何使用

2、结果:

A class: 2

B class: 1

python中 super()函数如何使用

3、python 2.x版本实现:super(子类名,self).父类方法

class A(object):

    def show(self,x):

        print('A class: {}'.format(x+1))

class B(A):

    def show1(self,x):

        super(B,self).show(x)

        print("B class: {}".format(x))

b=B()

b.show1(1)

python中 super()函数如何使用

4、运行结果:

A class: 2

B class: 1

python中 super()函数如何使用

5、实例:

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),然后把类B的对象 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')

python中 super()函数如何使用

6、运行结果:

Parent

Child

HelloWorld from Parent

Child bar fuction

I'm the parent.

python中 super()函数如何使用

  • Android手机如何安装卸载apk软件
  • Springmvc自定义过滤器Filter,解决跨域问题
  • M8832非隔离恒流LED驱动芯片 可替换CS7210
  • 精简版win10怎么下载安装
  • 晶丰明源与茂捷芯片替换
  • 热门搜索
    狗肉怎么做好吃 猪肚鸡的做法大全 怎么才能 为什么医生建议打二价 香菇怎么做好吃 微信建群怎么建 联想怎么进入bios 孩子不听话叛逆怎么办 潘凤为什么叫无双上将 为什么中秋节要吃月饼