多重继承

Python 面向对象编程进阶

Jake Roach

Data Engineer

多重继承

允许一个类继承多个类的功能

  • Intern 可同时继承 EmployeeStudent
  • 保持"是一个(is-a)"关系

Intern 类同时继承 Employee 与 Student 类。

class Employee:
  def __init__(self, department):
    self.department = department

  def begin_job(self):
    print(f"Welcome to {self.department}!")
class Student:
  def __init__(self, school):
    self.school = school
    self.courses = []

  def add_course(self, course_name):
    self.courses.append(course_name)
Python 面向对象编程进阶

多重继承

class Intern(Employee, Student):
    def __init__(self, department, school, duration):
        # 同时调用两个构造函数
        Employee.__init__(self, department)
        Student.__init__(self, school)
        self.duration = duration

    def onboard(self, mentor):
        # 新方法的实现
        ...
Python 面向对象编程进阶

创建 Intern 对象

stephen = Intern("Software Development", "Echo University", 10)
stephen.begin_job()  # Method from Employee
Welcome to Software Development!
stephen.add_course("Intermediate OOP in Python")  # Method from Intern
print(stephen.courses)
["Intermediate OOP in Python"]
Python 面向对象编程进阶

多级继承

继承一个已继承自另一类的类,成为"孙类"

  • 维持"是一个(is-a)"关系

多级继承示意图。

class Person:
  def __init__(self, name):
    self.name = name

  def introduce(self):
      print(f"Hello, my name is {self.name}")
class Employee(Person):
  def __init__(self, name, title):
    Person.__init__(self, name)
    self.title = title

  def change_position(self, new_title):
    print(f"Starting new role as {new_title}")
    self.title = new_title
Python 面向对象编程进阶

多级继承

class Manager(Employee):
  def __init__(self, name, title, number_reports):
    Employee.__init__(self, name, title)
    self.number_reports = number_reports

mike = Manager("Mike", "Engineering Manager", 14)
mike.introduce()
mike.change_position("Director of Engineering")
print(mike.number_reports)
Hello, my name is Mike
Starting new role as Director of Engineering
14
Python 面向对象编程进阶

方法解析顺序(MRO)

当父类与子类实现同名方法时,Python 决定调用哪个方法的顺序

确定 MRO 的规则:

  • 先从子类开始查找
  • 按类定义中的从左到右顺序查找父类

$$

.mro() 方法与 __mro__

子类继承多个父类。

1 Beyond the Basic Stuff with Python, Sweigart(第311页)
Python 面向对象编程进阶

方法解析顺序(MRO)

class Intern(Employee, Student):  # Intern inherits the Employee and the Student classes
  ...

# Find the MRO for Intern
print(Intern.mro())
[<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>]
# Find the MRO using __mro__
print(Intern.__mro__)
(<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>)
Python 面向对象编程进阶

让我们来练习!

Python 面向对象编程进阶

Preparing Video For Download...