python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python内置函数super()

Python中内置函数super()用法示例详解

作者:MediaTea

这篇文章主要介绍了Python中内置函数super()用法的相关资料,super()函数的主要作用是调用父类(超类)以及多层父类中的方法,这对于访问已在类中重写的继承方法很有用,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

在面向对象编程中,类常有继承关系,子类需要复用或扩展基类逻辑。Python 提供内置函数 super(),返回一个代理对象,用于按 MRO(方法解析顺序) 调用当前类之后的下一个类的方法。这样可以避免硬编码父类名,使代码在多继承下更健壮、可维护。

一、函数语法

super([type[, object-or-type]])

参数:

常见写法:

🔹实例方法

super().method(...)

# 等价于:
super(CurrentClass, self).method(...)

🔹类方法

@classmethod
def m(cls, ...):
    super().method(...)

# 等价于:
super(CurrentClass, cls).method(...)

返回值:

一个 super 代理对象,可用于调用 MRO 中“当前类之后的下一个类” 的方法。

提示:

Python 3 支持零参 super()。单参形式很少需要,一般用零参或两参。

二、基础用法示例

1、基本继承调用

class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()   # 调用父类方法
        print("Hello from Child")

c = Child()
c.greet()

# Hello from Parent
# Hello from Child

2、构造函数链

class A:
    def __init__(self):
        print("A init")

class B(A):
    def __init__(self):
        super().__init__()  # 调用 A.__init__()
        print("B init")

b = B()
# A init
# B init

三、进阶技巧

1、多继承与 MRO(方法解析顺序)

class A:
    def greet(self): 
        print("A")

class B(A):
    def greet(self): 
        super().greet()
        print("B")

class C(A):
    def greet(self):
        super().greet()
        print("C")

class D(B, C):
    def greet(self):
        super().greet()
        print("D")

d = D()
d.greet()

# A
# C
# B
# D

MRO 顺序:D → B → C → A → object。

super() 并非“父类调用”,而是沿 MRO 从当前类的后继继续向上。

2、显式两参 super()

当你不在方法定义的典型上下文(或需要手动指明上下文)时,可显式传入两参:

class Base:
    def who(self): print("Base.who")

class Sub(Base):
    def who(self):
        print("Sub.who → call super:")
        return super(Sub, self).who()

Sub().who()
# Sub.who → call super:
# Base.who

3、类方法与静态方法

类方法可直接零参 super()(因为有 cls):

class A:
    @classmethod
    def hello(cls):
        print("A hello")

class B(A):
    @classmethod
    def hello(cls):
        super().hello()
        print("B hello")

B.hello()

# A hello
# B hello

静态方法中没有隐式的 self/cls,零参 super() 不可用。但可以显式两参使用(调用无需实例的方法):

class A:
    @classmethod
    def ping(cls): print("A.ping")

class B(A):
    @staticmethod
    def call_ping():
        # 显式指定当前类与类型参数
        super(B, B).ping()

B.call_ping()
# A.ping

若要在静态方法中调用需要实例的方法,你必须自备实例并作为第二参传入(或改为实例/类方法设计)。

四、补充说明与常见误区

1、误把 super() 当“父类调用”

它依赖 MRO,是当前位置之后的下一个类;多继承下若某类不调用 super(),调用链会被中断。

2、静态方法并非完全不能 super()

不能用零参,但可以显式两参(见上例)。关键是你是否有合适的第二参数以及要调用的是否为可在该上下文调用的方法(如 @classmethod)。

3、签名与参数传递

在 __init__ 或其他需要链式调用的方法中,建议:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

以免在多继承组合时出现参数不匹配。

小结

super() 返回一个基于 MRO 的代理,不是“直接父类”的别名。

零参 super() 适用于实例方法与类方法;在静态方法或特殊上下文中,可用显式两参。

在多继承中配合合作式 super() 与一致的参数传递,能保证方法/构造链完整运行,避免菱形继承中的重复与遗漏。

到此这篇关于Python中内置函数super()用法的文章就介绍到这了,更多相关Python内置函数super()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文