多重繼承

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()  # 來自 Employee 的方法
Welcome to Software Development!
stephen.add_course("Intermediate OOP in Python")  # 來自 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 同時繼承 Employee 與 Student 類別
  ...

# 取得 Intern 的 MRO
print(Intern.mro())
[<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>]
# 使用 __mro__ 查詢 MRO
print(Intern.__mro__)
(<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>)
Python 物件導向程式設計進階

一起來練習吧!

Python 物件導向程式設計進階

Preparing Video For Download...