問題一覧に戻る
上級高度なパターン
問題111: 抽象基底クラス

抽象基底クラス(ABC)は、abcモジュールを使って定義され、サブクラスが実装すべきメソッドを定義します。ABCを継承し、@abstractmethodデコレータを付けたメソッドは、サブクラスで必ず実装しなければなりません。これにより、インターフェースの契約を強制でき、設計の一貫性を保てます。

# 抽象基底クラス
from abc import ,

# ABCを定義
class Shape():

def area(self):
pass

# ABCを実装
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

# 実装を使用
rect = Rectangle(5, 3)
print(rect.area())