抽象基底クラス

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

Jake Roach

Data Engineer

抽象基底クラス

抽象基底クラスは、すべての子クラスが実装すべき抽象メソッドを定義して、クラスの設計図を作る

  • 一群のクラスで共通の振る舞いを保証
  • @abstractmethod デコレータ
  • 継承して使い、直接インスタンス化しない
  • すべてを抽象にする必要はない(具体メソッドも可)
class School:
    # enroll などを行う
    # およびコース追加
class MiddleSchool:
    # 楽器やクラブに参加
    # ただし enroll とコース追加は必須
class HighSchool:
    # 部活動や大学出願
    # ただし enroll とコース追加は必須
Python 中級オブジェクト指向プログラミング

抽象基底クラスの作成

from abc import ABC, abstractmethod

# ABC を継承して抽象基底クラスを作成 class School(ABC): @abstractmethod def enroll(self): # 継承先で必ず実装する pass
# 具体メソッドは継承される def graduate(self): print("Congrats on graduating!")
  • abc モジュールの ABC を継承
  • pass
  • School を継承するクラスは enroll() を必ず実装
  • 具体メソッドも定義できる
Python 中級オブジェクト指向プログラミング

抽象基底クラスの実装

class HighSchool(School):
    def enroll(self):
        print("Welcome to high school!")

# Create an instance of HighSchool
high_school = HighSchool()
high_school.enroll()
Welcome to high school!
high_school.graduate()
Congrats on graduating!
  • HighSchoolenroll() を定義しなければならない
  • 未定義なら TypeError
  • HighSchoolgraduate() を継承
Python 中級オブジェクト指向プログラミング

複数の抽象メソッド

class School(ABC):
    @abstractmethod
    def enroll(self):
        pass

    @abstractmethod
    def add_course(self, course_name):
        pass

    def graduate(self):
        print("Congrats on graduating!")

  • 2つの抽象メソッド enroll()add_course()
class HighSchool(School):
    def __init__(self):
        self.courses = []

    # Implementing abstract method
    def enroll(self):
        print("Welcome to high school!")

    # Implementing abstract method
    def add_course(self, course_name):
        self.courses.append(course_name)
        print(f"You enrolled in {course_name}")

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

Passons à la pratique !

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

Preparing Video For Download...