Python 3 中的 super()

Python super

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

Python super 函数示例

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

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()

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

Person.__init__(self, student_name, student_age) 

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

super().__init__(student_name, student_age)

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

Python 3 super

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

class Person(object):
...
        super(Student, self).__init__(student_name, student_age)

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

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__() 函数,还可以调用父类的所有其他函数。因此,在下面的示例中,我们将看到这一点。

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

相关推荐

  1. Python 3 super()

    2024-02-12 11:52:01       51 阅读
  2. Python笔记-super().init(root)作用

    2024-02-12 11:52:01       53 阅读
  3. python super()笔记

    2024-02-12 11:52:01       53 阅读
  4. Reactsuper()和super(props)有什么区别?

    2024-02-12 11:52:01       59 阅读
  5. 如何理解Reactstate、props、super()和super(props)

    2024-02-12 11:52:01       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-12 11:52:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-12 11:52:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-12 11:52:01       82 阅读
  4. Python语言-面向对象

    2024-02-12 11:52:01       91 阅读

热门阅读

  1. MongoDB聚合:$unset

    2024-02-12 11:52:01       54 阅读
  2. C++局部变量与全局变量

    2024-02-12 11:52:01       49 阅读
  3. 类与结构体(4)

    2024-02-12 11:52:01       51 阅读
  4. 只要努力,便会有收获

    2024-02-12 11:52:01       54 阅读
  5. ansible 基本用法

    2024-02-12 11:52:01       70 阅读
  6. m1芯片xcode15编译cocos2dx一些报错处理

    2024-02-12 11:52:01       60 阅读
  7. 逗女孩开心的python代码合集

    2024-02-12 11:52:01       56 阅读