Python 简明教程

Python - Inheritance

What is Inheritance in Python?

Inheritance 是像 Python 这样的面向对象的编程语言中最重要的一些特性之一。它用于将一个类的属性和行为继承到另一个类。继承另一个类的类称为 child class 而被继承的类称为 base class or parent class

Inheritance is one of the most important features of object-oriented programming languages like Python. It is used to inherit the properties and behaviours of one class to another. The class that inherits another class is called a child class and the class that gets inherited is called a base class or parent class.

如果必须设计一个类,而它的许多属性在某个现有类中已经定义得很完善,那么为什么要重新定义它们呢?继承使得现有类的能力能够被重用,并且如果需要,可扩展到设计一个新类。

If you have to design a new class whose most of the attributes are already well defined in an existing class, then why redefine them? Inheritance allows capabilities of existing class to be reused and if required extended to design a new class.

当一个新类与一个现有类具有“是”关系时,就会用到继承。例如:轿车是一类车辆,公共汽车是一类车辆,摩托车也是一类车辆。在此,车辆是父类,而轿车、公共汽车和摩托车是子类。

Inheritance comes into picture when a new class possesses 'IS A' relationship with an existing class. For example, Car IS a vehicle, Bus IS a vehicle, Bike IS also a vehicle. Here, Vehicle is the parent class, whereas car, bus and bike are the child classes.

media folder

Creating a Parent Class

具有被继承的属性和方法的类称为父类。它的定义和其他类类似,即使用 class 关键字。

The class whose attributes and methods are inherited is called as parent class. It is defined just like other classes i.e. using the class keyword.

Syntax

创建父类的语法如下所示:

The syntax for creating a parent class is shown below −

class ParentClassName:
   {class body}

Creating a Child Class

从基类继承的子类声明与其父类类似;不过,我们需在圆括号内提供父类的名称。

Classes that inherit from base classes are declared similarly to their parent class, however, we need to provide the name of parent classes within the parentheses.

Syntax

以下是子类的语法:

Following is the syntax of child class −

class SubClassName (ParentClass1[, ParentClass2, ...]):
   {sub class body}

Types of Inheritance

在 Python 中,继承可分为五种不同的类别:

In Python, inheritance can be divided in five different categories −

  1. Single Inheritance

  2. Multiple Inheritance

  3. Multilevel Inheritance

  4. Hierarchical Inheritance

  5. Hybrid Inheritance

inheritance type in python

Python - Single Inheritance

这是继承的最简单形式,其中子类从一个父类继承属性和方法。

This is the simplest form of inheritance where a child class inherits attributes and methods from only one parent class.

Example

以下示例展示了 Python 中的单一继承概念:

The below example shows single inheritance concept in Python −

# parent class
class Parent:
   def parentMethod(self):
      print ("Calling parent method")

# child class
class Child(Parent):
   def childMethod(self):
      print ("Calling child method")

# instance of child
c = Child()
# calling method of child class
c.childMethod()
# calling method of parent class
c.parentMethod()

运行以上代码,它将打印以下结果:

On running the above code, it will print the following result −

Calling child method
Calling parent method

Python - Multiple Inheritance

Python 中的多个继承允许你基于一个以上的父类构建一个类。子类因此可以继承所有父类的属性和方法。子类可以覆盖从任何父类继承的方法。

Multiple inheritance in Python allows you to construct a class based on more than one parent classes. The Child class thus inherits the attributes and method from all parents. The child can override methods inherited from any parent.

Syntax

class parent1:
   #statements

class parent2:
   #statements

class child(parent1, parent2):
   #statements

Example

Python 的标准库有一个内置的 divmod()函数,该函数返回一个包含两个元素的元组。第一个数字是两个自变量的商,第二个是两个操作数的模值。

Python’s standard library has a built-in divmod() function that returns a two-item tuple. First number is the division of two arguments, the second is the mod value of the two operands.

此示例中尝试模拟 divmod()函数。我们定义了两个类,即 division 和 modulus,然后有一个 div_mod 类继承这两个类。

This example tries to emulate the divmod() function. We define two classes division and modulus, and then have a div_mod class that inherits them.

class division:
   def __init__(self, a,b):
      self.n=a
      self.d=b
   def divide(self):
      return self.n/self.d
class modulus:
   def __init__(self, a,b):
      self.n=a
      self.d=b
   def mod_divide(self):
      return self.n%self.d

class div_mod(division,modulus):
   def __init__(self, a,b):
      self.n=a
      self.d=b
   def div_and_mod(self):
      divval=division.divide(self)
      modval=modulus.mod_divide(self)
      return (divval, modval)

这个子类有一个新的方法 div_and_mod(),该方法在内部调用其继承类的 divide() 和 mod_divide() 方法以返回商和模值。

The child class has a new method div_and_mod() which internally calls the divide() and mod_divide() methods from its inherited classes to return the division and mod values.

x=div_mod(10,3)
print ("division:",x.divide())
print ("mod_division:",x.mod_divide())
print ("divmod:",x.div_and_mod())

Output

division: 3.3333333333333335
mod_division: 1
divmod: (3.3333333333333335, 1)

Method Resolution Order (MRO)

术语方法解析顺序与 Python 中的多个继承相关。在 Python 中,继承可以分布在多个层面上。我们假设 A 是 B 的父类,而 B 是 C 的父类。类 C 可以覆盖继承的方法,或者其对象可以按其父类中定义内容调用该方法。那么,Python 如何查找适当的方法进行调用。

The term method resolution order is related to multiple inheritance in Python. In Python, inheritance may be spread over more than one levels. Let us say A is the parent of B, and B the parent for C. The class C can override the inherited method or its object may invoke it as defined in its parent. So, how does Python find the appropriate method to call.

每个 Python 中都有一个 mro() 方法,该方法返回 Python 用于解析要调用的方法的层次顺序。解析顺序是从继承顺序的底部到顶部。

Each Python has a mro() method that returns the hierarchical order that Python uses to resolve the method to be called. The resolution order is from bottom of inheritance order to top.

在我们前面的示例中,div_mod 类继承了 division 类和 modulus 类。因此,mro 方法返回以下顺序:

In our previous example, the div_mod class inherits division and modulus classes. So, the mro method returns the order as follows −

[<class '__main__.div_mod'>, <class '__main__.division'>, <class '__main__.modulus'>, <class 'object'>]

Python - Multilevel Inheritance

在多层次继承中,一个类是从另一个派生类派生的。有多个继承层。我们可以将其想象为祖父母-父母-子女的关系。

In multilevel inheritance, a class is derived from another derived class. There exists multiple layers of inheritance. We can imagine it as a grandparent-parent-child relationship.

Example

在下面的示例中,我们将说明多层次继承的工作原理。

In the following example, we are illustrating the working of multilevel inheritance.

# parent class
class Universe:
   def universeMethod(self):
      print ("I am in the Universe")

# child class
class Earth(Universe):
   def earthMethod(self):
      print ("I am on Earth")

# another child class
class India(Earth):
   def indianMethod(self):
      print ("I am in India")

# creating instance
person = India()
# method calls
person.universeMethod()
person.earthMethod()
person.indianMethod()

执行上述代码时,它将产生以下结果:

When we execute the above code, it will produce the following result −

I am in the Universe
I am on Earth
I am in India

Python - Hierarchical Inheritance

此类型的继承包含从一个基类继承的多个派生类。这类似于组织内的层次结构。

This type of inheritance contains multiple derived classes that are inherited from a single base class. This is similar to the hierarchy within an organization.

Example

以下示例说明了层次继承。此处,我们定义了 Manager class 的两个子类。

The following example illustrates hierarchical inheritance. Here, we have defined two child classes of Manager class.

# parent class
class Manager:
   def managerMethod(self):
      print ("I am the Manager")

# child class
class Employee1(Manager):
   def employee1Method(self):
      print ("I am Employee one")

# second child class
class Employee2(Manager):
   def employee2Method(self):
      print ("I am Employee two")

# creating instances
emp1 = Employee1()
emp2 = Employee2()
# method calls
emp1.managerMethod()
emp1.employee1Method()
emp2.managerMethod()
emp2.employee2Method()

执行上述程序时,你将得到以下输出:

On executing the above program, you will get the following output −

I am the Manager
I am Employee one
I am the Manager
I am Employee two

Python - Hybrid Inheritance

将两种或多种类型的继承相结合称为混合继承。例如,它可以是单一继承和多重继承的一种混合。

Combination of two or more types of inheritance is called as Hybrid Inheritance. For instance, it could be a mix of single and multiple inheritance.

Example

在这个示例中,我们结合了单个和多个继承来形成类的混合继承。

In this example, we have combined single and multiple inheritance to form a hybrid inheritance of classes.

# parent class
class CEO:
   def ceoMethod(self):
      print ("I am the CEO")

class Manager(CEO):
   def managerMethod(self):
      print ("I am the Manager")

class Employee1(Manager):
   def employee1Method(self):
      print ("I am Employee one")

class Employee2(Manager, CEO):
   def employee2Method(self):
      print ("I am Employee two")

# creating instances
emp = Employee2()
# method calls
emp.managerMethod()
emp.ceoMethod()
emp.employee2Method()

运行上述程序将产生以下结果:

On running the above program, it will give the below result −

I am the Manager
I am the CEO
I am Employee two

The super() function

在 Python 中,super() 函数允许你从子类中访问父类的方法和属性。

In Python, super() function allows you to access methods and attributes of the parent class from within a child class.

Example

在以下示例中,我们创建一个父类,并使用 super() 函数从子类访问其构造函数。

In the following example, we create a parent class and access its constructor from a subclass using the super() function.

# parent class
class ParentDemo:
   def __init__(self, msg):
      self.message = msg

   def showMessage(self):
      print(self.message)

# child class
class ChildDemo(ParentDemo):
   def __init__(self, msg):
      # use of super function
      super().__init__(msg)

# creating instance
obj = ChildDemo("Welcome to Tutorialspoint!!")
obj.showMessage()

运行后,上述程序将产生以下结果:

On executing, the above program will give the following result −

Welcome to Tutorialspoint!!