Python super() – Python 3 super()

Python 的 super() 函数允许我们明确地引用父类。在继承的情况下很有用,当我们想要调用超类函数时。

Python super

要了解 Python super 函数,您必须了解 Python 继承。在 Python 继承中,子类继承自超类。Python 的 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  # returns the value of student 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超级函数与多层继承

正如我们先前所述,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超级函数

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

你可以从我们的[GitHub存储库](https://github.com)中查看完整的Python脚本和更多Python示例。

参考:[官方文档](https://docs.python.org/zh-cn/3/library/functions.html#super)

Source:
https://www.digitalocean.com/community/tutorials/python-super