super()函数用于调用父类的方法。当子类重写了父类的方法后,如果想要在子类中调用父类的方法,就可以使用super()函数。使用super()函数可以避免硬编码父类的名称,使代码更具可读性和可维护性。

函数语法

# Python 3 简化语法
super()
# 完整语法 Python 2/3 兼容
super(type, object_or_type)

完整语法参数:

  • type:当前类;
  • object-or-type:当前实例或当前类;

super()返回一个特殊的代理对象,它知道如何调用父类的方法。

super()函数示例

一个简单的示例:

class Parent:
    def method(self):
        print("Parent.method")

class Child(Parent):
    def method(self):
        #硬编码调用父类mehod方法
        Parent.method(self)
        #super简化方法(最常用)
        super().method()
        #完整super方法
        super(Child,self).method()

        print("Child.method")

obj = Child()
obj.method()

常用于初始化:

class Parent:
    def __init__(self):
        print("Parent __init__")

class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child __init__")

obj = Child()