Pythonにおける抽象クラスとインターフェースの違い 質問する

Pythonにおける抽象クラスとインターフェースの違い 質問する

Python の抽象クラスとインターフェースの違いは何ですか?

ベストアンサー1

時々目にするのは次のようなものです:

class Abstract1:
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""

    def aMethod(self):
        raise NotImplementedError("Should have implemented this")

Python には正式なインターフェース契約がないため (また必要ないため)、抽象とインターフェースの Java スタイルの区別は存在しません。正式なインターフェースを定義する努力をすれば、それは抽象クラスにもなります。唯一の違いは、docstring で述べられている意図にあります。

ダックタイピングを使用する場合、抽象とインターフェースの違いは微妙な問題になります。

Java には多重継承がないため、インターフェースを使用します。

Pythonには多重継承があるので、次のようなものも見られるかもしれません。

class SomeAbstraction:
    pass  # lots of stuff - but missing something

class Mixin1:
    def something(self):
        pass  # one implementation

class Mixin2:
    def something(self):
        pass  # another

class Concrete1(SomeAbstraction, Mixin1):
    pass

class Concrete2(SomeAbstraction, Mixin2):
    pass

これは、ミックスインを使用した一種の抽象スーパークラスを使用して、分離した具体的なサブクラスを作成します。

おすすめ記事