Python は抽象クラスを使用してインターフェースを定義する

Document 对象参考手册Python3 実例

Python では、抽象クラスはインスタンス化できず、継承のみが可能な特別なクラスです。抽象クラスは通常、インターフェース、つまり一連のメソッドの宣言を定義するために使用され、具体的な実装は提供しません。サブクラスはこれらのメソッドを実装して初めてインスタンス化できます。

Python は ... を提供していますabcモジュールを用いて抽象クラスを作成できます。私たちはABCクラスとabstractmethodデコレータを使用して抽象メソッドを定義できます。

以下は、抽象クラスを使用してインターフェースを定義する例です:

実例

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

    @abstractmethod
    def move(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

    def move(self):
        return "Running on four legs"

class Bird(Animal):
    def make_sound(self):
        return "Chirp!"

    def move(self):
        return "Flying in the sky"

# サブクラスをインスタンス化する
dog = Dog()
bird = Bird()

print(dog.make_sound())  # 出力: Woof!
print(dog.move())        # 出力: Running on four legs

print(bird.make_sound()) # 出力: Chirp!
print(bird.move())       # 出力: Flying in the sky

コード解説:

  1. Animalは抽象クラスであり、... から継承しますABC。それは ... と ... の2つの抽象メソッドを定義していますmake_soundとmove、これらのメソッドには具体的な実装がありません。
  2. DogとBirdであるAnimalのサブクラスであり、それらは ... を実装する必要がありますmake_soundとmoveメソッドを実装しない場合、... がスローされますTypeError。
  3. Dogクラスはmake_soundメソッドを実装し、"Woof!" を返し、さらにmoveメソッドを実装して "Running on four legs" を返します。
  4. Birdクラスはmake_soundメソッドを実装し、"Chirp!" を返し、さらにmoveメソッドを実装して "Flying in the sky" を返します。
  5. 最後に、私たちはDogとBirdクラスをインスタンス化し、それらのメソッドを呼び出しました。

出力結果:

Woof!
Running on four legs
Chirp!
Flying in the sky

Document 对象参考手册Python3 実例

その他の拡張