Python super函数
super函数的定义
super() 函数是用于调用父类或同级类的一个方法。
官方定义:Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
一、使用语法
super(type[, object-or-type])
- type 类
- object-or-type 对象或类(一般为self)
二、代码示例
#!/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.
结果分析:
1.首先执行fooChild = FooChild(),跳转到FooChild()的init函数内
2.因为FooChild 父类为FooParent。当执行FooChild的init函数内的super函数时,调用父类的init函数,输出Parent
3.继续FooChild的init函数,输出Child
4.之后执行 fooChild.bar(‘HelloWorld’)
5.执行super,跳转到父类bar函数,输出HelloWorld from Parent
6.顺着super之后继续执行,输出Child bar fuction和I’m the parent.