python super()函数介绍(允许子类访问其超类的方法)superclass父类、超类;subclass子类

理解Python中的super()函数(Understanding the super() Function in Python)

引言(Introduction)

The super() function in Python plays a crucial role in facilitating(促进) polymorphism(多态) and code reuse by enabling subclasses to access methods of their superclass. This article delves into the depths(深入探讨) of super(), covering its mechanisms, benefits, and practical applications with comprehensive examples.
Python中的super()函数在促进多态性和代码复用方面起着至关重要的作用,它允许子类访问其超类的方法。本文深入探讨了super()的机制、优势和实际应用,并提供了全面的示例。

什么是super()?(What is super()?)

In object-oriented programming, super() is a built-in function that returns a temporary(临时的) object of the superclass, allowing the subclass to access inherited methods that have been overridden(否决). This capability is essential for calling a method from the superclass from within a method in the subclass.
在面向对象编程中,super()是一个内置函数,它返回一个超类的临时对象,允许子类访问已被覆盖的继承方法。这一能力对于在子类的方法中调用超类的方法是必不可少的。

“This capability is essential for calling a method from the superclass
from within a method in the subclass.”

这个句子的结构确实有点复杂,主要因为它涉及层次和方向的关系。让我们一步一步分解:

  1. 主体和谓语:

    • 主体是"This capability"(这项能力)。
    • 谓语是"is essential"(是必不可少的)。
  2. 目的:

    • 短语"for calling a method from the superclass"(为了从超类调用一个方法)说明了这项能力的用途。
    • "for"引导的是目的状语,说明这项能力的用途或目的。
  3. 方位和范围:

    • “from within a method in the subclass”(在子类的一个方法内部)说明了调用的环境或范围。
    • “from within"是一个固定搭配,表示"从…里面”。
    • “a method in the subclass”(子类中的一个方法)指明了这个行为发生的具体位置。
  4. 两个"from"的区别:

    • 第一个"from"在"from the superclass"中用来指代方法的来源,即方法定义在哪个类中。
    • 第二个"from"是"from within"的一部分,用来描述行为的发生位置,即在子类的方法内部。

综上所述,这句话的意思是:这项能力对于在子类的方法内部调用超类中定义的方法来说是必不可少的。简而言之,它描述的是一个子类如何能够访问并调用其超类中的方法,这对于实现代码的重用和扩展非常重要。

为什么使用super()?(Why Use super()?)

避免写死

  • Avoids Hardcoding: By using super(), the superclass name does not need to be hardcoded, making the code more maintainable(可维护的) and adaptable(能适应的) to changes.
    避免硬编码: 通过使用super(),不需要硬编码超类名称,使得代码更加可维护和适应变化。

多重继承

  • Multiple Inheritance(遗产继承): It plays a critical role in the context of multiple inheritance, ensuring that the correct superclass methods are called in the right order.
    多重继承: 它在多重继承的上下文中扮演着关键角色,确保以正确的顺序调用正确的超类方法。

super()是如何工作的?(How Does super() Work?)

单继承(Single Inheritance)

In a single inheritance scenario, super() allows us to call methods of the superclass from within the subclass without explicitly(明确的) naming(说出…的名称;准确陈述) the superclass.
在单继承场景中,super()允许我们在子类内部调用超类的方法,而无需显式地命名超类。

示例:(Example:)
class Animal:
    def __init__(self, name):
        self.name = name


class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # No need to use Animal.__init__(self, name)
        self.breed = breed      # 品种


dog = Dog("Buddy", "Golden Retriever")
print(dog.name)  # Outputs: Buddy
print(dog.breed)  # Outputs: Golden Retriever(金毛寻回犬)

多重继承(Multiple Inheritance)

When dealing with multiple inheritance, super() ensures that methods from all bases are called in the proper order, following the Method Resolution Order (MRO).
在处理多重继承时,super()确保按照方法解析顺序(MRO)以正确的顺序调用所有基类的方法。

示例:(Example:)
class BaseClass:
    def __init__(self):
        print("BaseClass __init__")


class FirstLevel(BaseClass):
    def __init__(self):
        super().__init__()
        print("FirstLevel __init__")


class SecondLevel(BaseClass):
    def __init__(self):
        super().__init__()
        print("SecondLevel __init__")


class ThirdLevel(FirstLevel, SecondLevel):
    def __init__(self):
        super().__init__()  # This follows MRO
        print("ThirdLevel __init__")


ThirdLevel()
# Expected Output:
# BaseClass __init__
# SecondLevel __init__
# FirstLevel __init__
# ThirdLevel __init__

print(ThirdLevel.mro())
# [<class '__main__.ThirdLevel'>, <class '__main__.FirstLevel'>, <class '__main__.SecondLevel'>, <class '__main__.BaseClass'>, <class 'object'>]

MRO 定义了类继承体系中方法和属性查找的顺序,当使用 super() 调用方法时,Python 就是按照这个顺序来确定下一个应该被调用的方法是什么。

在你提供的例子中,ThirdLevel.mro() 输出的顺序是:

  1. ThirdLevel
  2. FirstLevel
  3. SecondLevel
  4. BaseClass
  5. object

这正是 Python 解释器查找方法和属性时遵循的顺序。当你创建了一个 ThirdLevel 的实例并调用其 __init__ 方法时,Python 会首先尝试在 ThirdLevel 中找到 __init__。找到后,因为 ThirdLevel.__init__ 中使用了 super().__init__(),Python 会继续按照 MRO 顺序查找下一个类,即 FirstLevel

但这里的关键在于 super() 的工作方式。当 super().__init__() 被调用时,它会查找 MRO 中当前类之后的类中的 __init__ 方法。所以,尽管 MRO 显示的顺序是 FirstLevelSecondLevel 之前,super() 调用在 FirstLevel.__init__ 中会跳到 SecondLevel,因为 SecondLevel 是在 MRO 中 FirstLevel 之后的下一个类。

这就解释了为什么输出是:

  1. "BaseClass __init__"
  2. "SecondLevel __init__"
  3. "FirstLevel __init__"
  4. "ThirdLevel __init__"

实际的调用顺序是按照 super() 调用在代码中出现的顺序来决定的,结合 MRO 来确定下一个调用的具体是哪个类的方法。所以,在多重继承的情况下,super() 提供了一种方式来确保所有基类的方法都按照 MRO 顺序被适当地调用。

super()的高级用法(Advanced Usage of super()

动态分派(Dynamic Dispatch)

super() enables a form of dynamic dispatch when used in a method that is overridden in multiple subclasses. This can be especially useful in complex inheritance hierarchies.
当在多个子类中被重写的方法中使用时,super()可以实现一种动态分派的形式。这在复杂的继承体系中尤其有用。

调用其他方法(Calling Other Methods)

While super() is often used in constructors (__init__), it’s not limited to them. It can be used to call any method of the superclass.
虽然super()经常用在构造函数(__init__)中,但它不仅限于此。它可以用来调用超类的任何方法。

示例:(Example:)
class Vehicle:
    def start(self):
        print("Vehicle engine started")


class Car(Vehicle):
    def start(self):
        super().start()  # Calls Vehicle's start method
        print("Car engine started")


car = Car()
car.start()
# Expected Output:
# Vehicle engine started
# Car engine started

使用super()的提示(Tips for Using super()

  • Always use super() in a consistent manner(一致的方式) throughout(自始至终;贯穿整个时期) the inheritance hierarchy to avoid unexpected behaviors.
    在整个继承体系中始终以一致的方式使用super(),以避免意外行为。

  • Be cautious with super() in dynamic environments where the inheritance hierarchy may change, as it relies on the MRO.
    在继承体系可能变化的动态环境中使用super()时要小心,因为它依赖于MRO。

  • Understand the MRO in the context of multiple inheritance to predict the order in which methods will be called.
    在多重继承的上下文中理解MRO,以预测方法将被调用的顺序。

结论(Conclusion)

The super() function in Python is a powerful tool for object-oriented programming, enabling efficient and maintainable code through method reuse and polymorphism. Whether in simple single inheritance or complex multiple inheritance scenarios, super() simplifies(简化) calling superclass methods, promoting code reuse and maintainability. As(正如) demonstrated through examples, mastering super() is essential for any Python programmer looking to(希望,指望) leverage(利用) the full potential of object-oriented programming.
Python中的super()函数是面向对象编程的强大工具,通过方法重用和多态性实现了高效且可维护的代码。无论是在简单的单继承还是复杂的多重继承场景中,super()都简化了调用超类方法的过程,促进了代码的重用和可维护性。正如示例所演示的,掌握super()对于任何希望充分利用面向对象编程潜力的Python程序员来说都是必不可少的。

最近更新

  1. TCP协议是安全的吗?

    2024-03-25 04:26:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-25 04:26:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-25 04:26:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-25 04:26:04       20 阅读

热门阅读

  1. c++和c语言的区别实例

    2024-03-25 04:26:04       18 阅读
  2. 再次度过我的创作纪念日

    2024-03-25 04:26:04       15 阅读
  3. MySQL索引介绍

    2024-03-25 04:26:04       18 阅读
  4. Qt笔记 事件分发

    2024-03-25 04:26:04       18 阅读
  5. Qt:使用ctrl+z快捷键取消文本框修改

    2024-03-25 04:26:04       16 阅读
  6. Android Selinux详解[七]--如何给可执行程序bin加标签

    2024-03-25 04:26:04       15 阅读
  7. ES间的导数脚本

    2024-03-25 04:26:04       17 阅读
  8. clickhouse介绍

    2024-03-25 04:26:04       20 阅读
  9. 如何借助API提升产品设计的用户体验

    2024-03-25 04:26:04       18 阅读