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