abc というライブラリに、抽象クラスを定義する abc.ABCMeta と、デコレータで抽象メソッドを定義する abc.abstractmethod があります。
本項では、抽象クラスの定義方法について解説します。
以下は、Base という抽象クラスの定義です。Base は抽象メソッドである func() を持っています。
>>> from abc import ABCMeta >>> from abc import abstractmethod # Baseを抽象クラスとして定義 >>> class Base(metaclass=ABCMeta): ... # func()を抽象メソッドとして定義 ... @abstractmethod ... func(self): ... pass ...
Base は抽象クラスですので、そのまま実体化しようとすると、エラーになります。
>>> base = Base() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class Base with abstract methods func
また、Base を継承したクラスで、抽象メソッドを具体化していない場合も、エラーとなります。
# Baseを継承するクラス。 # 抽象メソッドを具体化していない。 >>> class Derived(Base): ... pass ... # 実体化できない >>> derived = Derived() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class Derived with abstract methods func
Base を継承した非抽象クラスを定義するには、抽象メソッドを具体化する必要があります。
# Baseを継承するクラス。
# 抽象メソッドを具体化している。
>>> class Derived(Base):
... def func(self):
... print('not abstract')
...
# 実体化可能
>>> derived = Derived()
>>> derived.func()
not abstract
0 件のコメント:
コメントを投稿