Python Using Abstract Classes to Define Interfaces
In Python, an abstract class is a special kind of class that cannot be instantiated and can only be inherited. Abstract classes are usually used to define interfaces, that is, a set of method declarations without concrete implementations. Subclasses must implement these methods before they can be instantiated.
Python provides the abc module to create abstract classes. We can use the ABC class and abstractmethod decorator to define abstract methods.
Below is an example of defining an interface with an abstract class:
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
(
)
(
dog.
make_sound
(
)
)
Output: Woof!
(
dog.
move
(
)
)
Output: Running on four legs
(
bird.
make_sound
(
)
)
Output: Chirp!
(
bird.
move
(
)
)
Output: Flying in the sky
Code analysis:
Animalis an abstract class that inherits fromABC. It defines two abstract methodsmake_soundandmove, and these methods have no concrete implementation.DogandBirdIsAnimal's subclasses, and they must implement themake_soundandmovemethod, otherwise they will throwTypeError。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 sky
Python3 Examples