Python继承怎么用?类继承语法和示例详解

文章导读
上一个 测验 下一个 Python 中的继承是什么? Inheritance(继承)是像 Python 这样的面向对象编程语言中最重要的特性之一。它用于将一个 class 的属性和行为继承到另一个 class。继承另一个 class 的 class 称为 child cla
📋 目录
  1. A Python 中的继承是什么?
  2. B 创建 Parent Class
  3. C 创建 Child Class
  4. D Inheritance 的类型
  5. E Python - Single Inheritance
  6. F Python - 多重继承
  7. G 方法解析顺序 (MRO)
  8. H Python - 多层继承
  9. I Python - 层次继承
  10. J Python - 混合继承
A A

Python - 继承



上一个
测验
下一个

Python 中的继承是什么?

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

如果您需要设计一个新 class,而其大部分属性已经在现有 class 中定义良好,那么为什么要重新定义它们呢?Inheritance 允许重用现有 class 的功能,并在需要时扩展以设计新 class。

当一个新 class 与现有 class 具有“IS A”(是一种)关系时,就会涉及 Inheritance。例如,Car IS a vehicle(汽车是一种车辆),Bus IS a vehicle(公交车是一种车辆),Bike IS also a vehicle(摩托车也是一种车辆)。在这里,Vehicle 是 parent class,而 car、bus 和 bike 是 child classes。

inheritance

创建 Parent Class

其属性和方法被继承的 class 称为 parent class。它与其他 class 一样使用 class 关键字定义。

语法

创建 parent class 的语法如下所示 −

class ParentClassName:
   {class body}

创建 Child Class

从 base class 继承的 class 的声明方式与其 parent class 类似,但是需要在括号中提供 parent class 的名称。

语法

以下是 child class 的语法 −

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

Inheritance 的类型

在 Python 中,inheritance 可以分为五种不同类别 −

  • Single Inheritance(单继承)
  • Multiple Inheritance(多继承)
  • Multilevel Inheritance(多级继承)
  • Hierarchical Inheritance(层次继承)
  • Hybrid Inheritance(混合继承)
types of inheritance

Python - Single Inheritance

这是最简单的 inheritance 形式,其中 child class 只从一个 parent class 继承属性和方法。

示例

下面的示例展示了 Python 中的 single inheritance 概念 −

# parent class(父类)
class Parent: 
   def parentMethod(self):
      print ("调用父类方法")

# child class(子类)
class Child(Parent): 
   def childMethod(self):
      print ("调用子类方法")

# child 的实例
c = Child()  
# 调用子类方法
c.childMethod() 
# 调用父类方法
c.parentMethod() 

运行上述代码,将输出以下结果 −

Calling child method
Calling parent method

Python - 多重继承

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

语法

class parent1:
   #语句
   
class parent2:
   #语句
   
class child(parent1, parent2):
   #语句

示例

Python 的标准库有一个内置的 divmod() 函数,它返回一个包含两个元素的元组。第一个数字是两个参数的除法结果,第二个是两个操作数的模值。

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

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() 方法,以返回除法和模值。

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

输出

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

方法解析顺序 (MRO)

术语 method resolution order 与 Python 中的多重继承相关。在 Python 中,继承可能跨越多个层级。假设 A 是 B 的父类,B 是 C 的父类。类 C 可以覆盖继承的方法,或者其对象可以调用父类中定义的方法。那么,Python 如何找到要调用的合适方法呢。

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

在之前的示例中,div_mod 类继承了 division 和 modulus 类。因此,mro 方法返回如下顺序 −

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

Python - 多层继承

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

示例

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

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

# 子类
class Earth(Universe): 
   def earthMethod(self):
      print ("I am on Earth")
      
# 另一个子类
class India(Earth): 
   def indianMethod(self):
      print ("I am in India")      

# 创建实例 
person = India()  
# 方法调用
person.universeMethod() 
person.earthMethod() 
person.indianMethod() 

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

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

Python - 层次继承

这种继承类型包含多个从单个基类继承的派生类。这类似于组织内部的层级结构。

示例

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

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

# 子类
class Employee1(Manager): 
   def employee1Method(self):
      print ("I am Employee one")
      
# 第二个子类
class Employee2(Manager): 
   def employee2Method(self):
      print ("I am Employee two")      

# 创建实例 
emp1 = Employee1()  
emp2 = Employee2()
# 方法调用
emp1.managerMethod() 
emp1.employee1Method()
emp2.managerMethod() 
emp2.employee2Method()  

执行上述程序后,您将得到以下输出 −

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

Python - 混合继承

两种或多种继承类型的组合称为混合继承。例如,它可以是单继承和多继承的混合。

示例

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

# 父类
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")      

# 创建实例 
emp = Employee2()
# 方法调用
emp.managerMethod() 
emp.ceoMethod()
emp.employee2Method()

运行上述程序,将得到以下结果 −

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

super() 函数

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

示例

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

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

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

# 子类
class ChildDemo(ParentDemo):
   def __init__(self, msg):
      # 使用 super 函数
      super().__init__(msg)  

# 创建实例
obj = ChildDemo("Welcome to !!")
obj.showMessage()  

执行上述程序,将得到以下结果 −

Welcome to !!