Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

36. Python 父类

函数允许我们显式地引用父类。在我们要调用父类函数的继承情况下,它很有用。

Python Super

要了解Python super() 函数,您必须了解Python继承. 在Python继承中,子类从父类继承。

函数允许我们隐式引用父类。因此,Python super使我们的任务更轻松、更舒适。当从子类引用父类时,我们不需要显式地写父类的名称。在下面几节中,我们将讨论Python super() 函数。

Python Super示例

首先,看看我们在Python继承辅导的。在该示例代码中,父类是Person and the subclass was Student. So the code is shown below.


class Person:
    # initializing the variables
    name = ""
    age = 0

    # defining constructor
    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

        # defining class methods

    def show_name(self):
        print(self.name)

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


# definition of subclass starts here
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


# end of subclass definition


# Create an object of the superclass
person1 = Person("Richard", 23)
# call member methods of the objects
person1.show_age()
# Create an object of the subclass
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

注意,上面的语法是针对python3超级函数的。如果您使用的是python 2.x版本,那么它会稍有不同,您必须进行以下更改:


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

第一个改变是object as the base class for Person. It’s required to use the super function in Python 2.x versions. Otherwise, you will get the following error.


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

超级函数本身语法的第二个变化。

如您所见,python3super函数更易于使用,语法也很整洁。

具有多级继承的Python Super

如前所述,Python super()函数允许我们隐式引用父类。

但是在多级继承的情况下,它将引用哪个类?好吧,Python super()总是引用直接父类。

而且Python super()函数不仅可以引用__init__() function but also can call all other function of the superclass. So, in the following example, we will see that.


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)

让我们看看上面的python3超级示例的输出,该示例具有多级继承。


Initializing: class C
Initializing: class B
Initializing: class A
Printing from class C: 1
Printing from class B: 2
Printing from class A: 3

因此,从输出中我们可以清楚地看到__init__() function of class C had been called at first, then class B and after that class A. Similar thing happened by calling sub_method() function.

为什么我们需要Python Super

如果您以前有过Java语言的经验,那么您应该知道基类也是由超级的反对。所以,这个概念实际上对编码人员很有用。但是,Python还保留了程序员使用父类名来引用它们的功能。而且,如果您的程序包含多级继承,那么这个super()函数对您很有帮助。

这就是Python super() 函数的全部内容。希望你能理解这个话题。请使用注释框进行任何查询。

您可以从我们的GitHub存储库.

参考文献:官方文件