Python Using Abstract Classes to Define Interfaces

Document 对象参考手册Python3 Examples

In Python, an abstract class is a special class that cannot be instantiated, only inherited. Abstract classes are typically used to define interfaces, i.e., declarations of a set of methods without providing concrete implementations. Subclasses must implement these methods in order to be instantiated.

Python provides theabcmodule to create abstract classes. We can use theABCclass and theabstractmethoddecorator to define abstract methods.

Below is an example of using an abstract class to define an interface:

Example

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"

# Instantiate the subclasses
dog = Dog()
bird = Bird()

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

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

Code explanation:

  1. Animalis an abstract class, inheriting fromABC. It defines two abstract methodsmake_soundandmove, which have no concrete implementation.
  2. DogandBirdYesAnimalsubclasses, they must implement themake_soundandmovemethods, otherwise it will raiseTypeError。
  3. Dogclass implements themake_soundmethod, returning "Woof!", and implements themovemethod, returning "Running on four legs".
  4. Birdclass implements themake_soundmethod, returning "Chirp!", and implements themovemethod, returning "Flying in the sky".
  5. Finally, we instantiated theDogandBirdclasses and called their methods.

Output result:

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

Document 对象参考手册Python3 Examples

Other Extensions