Python 3 中的 super()

Python super

Python 的 super() 函数允许我们显式地引用父类。在继承的情况下,当我们想要调用父类函数时,它非常有用。

Python super 函数示例

首先,让我们看一下我们在 Python 继承教程中使用的以下代码。在该示例代码中,父类是 Person,子类是 Student。代码如下所示。

python 复制代码
class Person:
    # 初始化变量
    name = ""
    age = 0

    # 定义构造函数
    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

    # 定义类方法
    def show_name(self):
        print(self.name)

    def show_age(self):
        print(self.age)


# 子类定义开始
class Student(Person):
    studentId = ""

    def __init__(self, student_name, student_age, student_id):
        Person.__init__(self, student_name, student_age)
        self.studentId = student_id

    def get_id(self):
        return self.studentId  # 返回学生 ID 的值


# 子类定义结束

# 创建父类对象
person1 = Person("Richard", 23)
# 调用对象的成员方法
person1.show_age()
# 创建子类对象
student1 = Student("Max", 22, "102")
print(student1.get_id())
student1.show_name()

在上面的示例中,我们调用了父类函数如下:

python 复制代码
Person.__init__(self, student_name, student_age) 

我们可以用以下方式替换为 python super 函数调用。

python 复制代码
super().__init__(student_name, student_age)

输出在两种情况下都将保持不变,如下图所示。

Python 3 super

请注意,上述语法适用于 Python 3 的 super 函数。如果你使用的是 Python 2.x 版本,则略有不同,你需要做以下更改:

python 复制代码
class Person(object):
...
        super(Student, self).__init__(student_name, student_age)

第一个更改是将 object 作为 Person 的基类。在 Python 2.x 版本中使用 super 函数是必需的。否则,你将会收到以下错误。

python 复制代码
Traceback (most recent call last):
  File "super_example.py", line 40, in <module>
    student1 = Student("Max", 22, "102")
  File "super_example.py", line 25, in __init__
    super(Student, self).__init__(student_name, student_age)
TypeError: must be type, not classobj

super 函数本身的语法也有所改变。正如你所看到的,Python 3 的 super 函数使用起来更加简单,语法也更加清晰。

Python super 函数与多层继承

正如我们之前所述,Python 的 super() 函数允许我们隐式地引用父类。但在多层继承的情况下,它将引用哪个类呢?好吧,Python 的 super() 总是引用直接的父类。此外,Python 的 super() 函数不仅可以引用 __init__() 函数,还可以调用父类的所有其他函数。因此,在下面的示例中,我们将看到这一点。

python 复制代码
class A:
    def __init__(self):
        print('Initializing: class A')

    def sub_method(self, b):
        print('Printing from class A:', b)


class B(A):
    def __init__(self):
        print('Initializing: class B')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class B:', b)
        super().sub_method(b + 1)


class C(B):
    def __init__(self):
        print('Initializing: class C')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class C:', b)
        super().sub_method(b + 1)


if __name__ == '__main__':
    c = C()
    c.sub_method(1)

让我们看看上述 Python 3 多层继承的示例输出。

复制代码
Initializing: class C
Initializing: class B
Initializing: class A
Printing from class C: 1
Printing from class B: 2
Printing from class A: 3

因此,从输出中我们可以清楚地看到,首先调用了类 C 的 __init__() 函数,然后是类 B,最后是类 A。通过调用 sub_method() 函数也发生了类似的事情。

为什么我们需要 Python 的 super 函数

如果你之前有 Java 语言的经验,那么你应该知道在那里也称为 super 对象的基类。因此,这个概念对于程序员来说实际上是有用的。然而,Python 也保留了使用超类名称来引用它们的功能。而且,如果你的程序包含多层继承,那么这个 super() 函数对你很有帮助。所以,这就是关于 Python super 函数的全部内容。希望你理解了这个主题。如果有任何疑问,请在评论框中提问。

相关推荐
Thanks_ks8 小时前
提示词工程实战:用结构化提示词让大模型输出稳定可控
python·大模型·json·openai·提示词工程·deepseek·系统提示词
BK贝壳10 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
ZhengEnCi10 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
吴名氏.11 小时前
全栈跃迁:Java 后端 27 讲【3】Vue3工程化脚手架
java·开发语言·springboot·全栈工程师
codeejun11 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
小此方13 小时前
QT从入门到精通(一)Qt新手保姆级教程:从官网安装到项目实战,四步带你彻底搞懂Qt框架
开发语言·qt
瑶池酒剑仙14 小时前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio
用户03321266636714 小时前
使用 Python 为 PDF 文件添加页眉页脚
python
xurileidian14 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
郝学胜-神的一滴15 小时前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy