pythonsuper函数_python super()函数

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

super()的语法:

python 2 的用法:

super(Class, self).xxx # class是子类的名称

class A(object):

pass

class B(a):

def add(self, x):

super(B,self).add(x)

python 3用法:

super().xxx

class A:

pass

class B(A):

def add(self, x):

super().add(x)

实例:

# _*_ coding:utf-8 _*_

class FooParent:

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).__init__() # 把FooChild对象转化成FooParent的对象,调用父类里的__init__(self),会输出‘parent'

self.child = 'this is child'

print('child') # 上一步调用结束后,打印‘child'

def bar(self, message):

super(FooChild, self).bar(message) # 调用父类里的bar函数

print('child bar function')

print(self.parent) # 打印父类的属性parent

print(self.child)

if __name__ == '__main__':

fooChild = FooChild()

fooChild.bar('HelloWorld')

输出结果

parent

child

HelloWorld from Parent

child bar function

I'm the parent

this is child

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值