Python 中的继承类型

17 Mar 2025 | 4 分钟阅读

继承是类的特定能力,它能够获取或继承另一个类的属性,然后在需要时使用它们。继承具有以下特征:

  • 它是对现实世界中关系的极佳体现。
  • 它允许代码重用。它不需要我们一遍又一遍地重复创建相同的代码。它还允许我们在不修改现有代码的情况下向现有类添加选项。
  • 它具有传递性,这意味着如果 B 类继承自另一个类 A,那么 B 类所属的所有子类都将直接继承自类 A。

示例

输出

Jackie False
johnny True

Python 中的继承类型

继承的类型取决于涉及的子类和父类的数量。Python 中有四种继承方式:

单继承 单继承允许派生类继承一个父类的属性,这使得代码重用和在现有代码中引入额外功能成为可能。

Types of inheritance Python

示例

输出

This function is defined inside the parent class.
This function is defined inside the child class.

多重继承 如果一个类能够由多个基类创建,则这种继承称为多重继承。在多重继承中,基类中的所有属性都会被传递给从它派生的类。

Types of inheritance Python

示例

输出

Father name is : Rajesh
Mother name is : Shreya

多层继承,原始类以及从它派生的类的功能都会被传递给新类。它类似于祖父母和子女之间的关系。

Types of inheritance Python

示例

输出

John Jr Jr
Grandfather name is : John Jr Jr
Father name is : John Jr
Son name is : John

层次继承 如果从同一个基类创建了多个派生类,则这种继承称为层次继承。在这种情况下,我们有两个作为父(基)类的基类以及两个作为子(派生)类的派生类。

Types of inheritance Python

示例

输出

This function is defined inside the parent class.
This function is defined inside the child 1.
This function is defined inside the parent class.
This function is defined inside the child 2.