- pythonでインターフェイスのようなことをやりたい場合にはABCモジュールというのが使えるようだ。
- でも、あんまり使っている印象はなく、raise NotImplementedErrorで簡易的に代用している場合が多いようだ。
ABCモジュールを使わない場合
- 簡易的にraise NotImplemntedError例外を出す。
- インスタンスの生成自体はできてしまう。
- エラーが発生するのはf()の実行時。
class Parent:
def f(self):
raise NotImplementedError
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
pass
if __name__ == '__main__':
c = Child()
c.f()
ABCモジュールを使う場合
- 使わない場合との違いは、f()を実装しないとインスタンスの生成時点でエラーが発生する。
from abc import ABCMeta, abstractmethod
class Parent(metaclass=ABCMeta):
@abstractmethod
def f(self):
raise NotImplementedError
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
pass
if __name__ == '__main__':
c = Child()