多重継承

Python 中級オブジェクト指向プログラミング

Jake Roach

Data Engineer

多重継承

1つのクラスが複数のクラスの機能を継承できる

  • InternEmployeeStudent の両方を継承可能
  • 「〜は…である」(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(p. 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__ で確認
print(Intern.__mro__)
(<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>)
Python 中級オブジェクト指向プログラミング

演習に進みましょう!

Python 中級オブジェクト指向プログラミング

Preparing Video For Download...