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 函数的全部内容。希望你理解了这个主题。如果有任何疑问,请在评论框中提问。

相关推荐
benchmark_cc8 小时前
A 股、港股、美股如何建立统一的标的主数据格式?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
维克兜率天8 小时前
【维克】趋势型CTA:期货市场的“追涨杀跌“
人工智能·python
Zenova EdgeOS9 小时前
Go 工业边缘错误处理实战:用 errors 构建可追溯错误链
开发语言·数据库·golang
取名真是9 小时前
Python 算法知识点从基础到进阶
开发语言·python·算法
梦想不只是梦与想9 小时前
PyTorch、CPU、GPU、CUDA
人工智能·pytorch·python·深度学习·机器学习·cuda
数字融合9 小时前
透明化视频孪生危化安全管控解决方案
人工智能·python·安全
FRing0310 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
Fatbobman(东坡肘子)11 小时前
快速消失的硬盘容量 -- 肘子的 Swift 周报 #160
开发语言·人工智能·redis·ios·swiftui·iphone·swift
揽星河..11 小时前
【C语言】底层程序设计
c语言·开发语言
JavaPub-rodert11 小时前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang