Python Using Abstract Classes to Define Interfaces
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
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:
Animalis an abstract class, inheriting fromABC. It defines two abstract methodsmake_soundandmove, which have no concrete implementation.DogandBirdYesAnimalsubclasses, they must implement themake_soundandmovemethods, otherwise it will raiseTypeError。Dogclass implements themake_soundmethod, returning "Woof!", and implements themovemethod, returning "Running on four legs".Birdclass implements themake_soundmethod, returning "Chirp!", and implements themovemethod, returning "Flying in the sky".- Finally, we instantiated the
DogandBirdclasses and called their methods.
Output result:
Woof! Running on four legs Chirp! Flying in the skyOther Extensions
Python3 Examples