super()函数是用来调用父类的方法。
其用法分为两步:
1、找到父类;
2、调用父类对应的方法。
实例1:
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):
#继承自父类FooParent
def __init__(self):
super(FooChild,self).__init__()
# super(FooChild,self):首先找到 FooChild 的父类(就是类 FooParent)
# 然后调用父类 FooParent 的方法
print ('Child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
fooChild = FooChild()
fooChild.bar('HelloWorld')
执行结果为:
Parent
Child
HelloWorld from Parent
Child bar fuction
I\'m the parent
实例2:
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x)
#相当于super(B,self).add(x),不写的时侯默认是自己
b = B()
b.add(2) # 3