Abstract Base Classes (ABC) provide a way to define abstract classes, which are classes that cannot be instantiated on their own and are meant to be subclassed.
An abstract class can define methods that must be implemented by any concrete subclass, ensuring a consistent interface across different implementations. The abc
module in Python allows you to create these abstract base classes.
from abc import ABC, abstractmethod
# Define an abstract base class
class Animal(ABC):
@abstractmethod
def sound(self):
pass
@abstractmethod
def move(self):
pass
# Concrete subclass must implement the abstract methods
class Dog(Animal):
def sound(self):
return "Bark"
def move(self):
return "Run"
class Fish(Animal):
def sound(self):
return "Blub"
def move(self):
return "Swim"
# Attempting to instantiate an abstract class raises an error
# animal = Animal() # This would raise TypeError
# Instantiate the concrete subclasses
dog = Dog()
fish = Fish()
print(f"The dog goes: {dog.sound()} and it can: {dog.move()}")
print(f"The fish goes: {fish.sound()} and it can: {fish.move()}")
Importing the abc
Module:
ABC
and abstractmethod
from the abc
module. ABC
is the base class for defining abstract base classes, and abstractmethod
is used to declare abstract methods that must be implemented by any subclass.Defining the Abstract Base Class:
Animal
by inheriting from ABC
. This class includes two abstract methods: sound()
and move()
. These methods are decorated with @abstractmethod
, which marks them as abstract methods. Abstract methods do not provide an implementation and must be overridden in any subclass of Animal
.Creating Concrete Subclasses:
Dog
and Fish
, that inherit from the Animal
class. Both subclasses implement the sound()
and move()
methods.Dog
implements sound()
to return “Bark” and move()
to return “Run”.Fish
implements sound()
to return “Blub” and move()
to return “Swim”.Instantiating Concrete Classes:
Dog
and Fish
. These instances are valid because the concrete subclasses provide implementations for all abstract methods defined in the Animal
class.Preventing Instantiation of the Abstract Class:
Animal
class directly (animal = Animal()
), it will raise a TypeError
because Animal
contains abstract methods and cannot be instantiated.Using the Concrete Subclass Instances:
sound()
and move()
methods on instances of Dog
and Fish
. This demonstrates that each subclass adheres to the interface defined by the abstract base class while providing its own specific implementation.Abstract Base Classes are used to enforce a common interface across multiple subclasses. This is particularly useful in large projects where different components need to work together, and it’s important to ensure that they all follow the same structure.
ABC
and abstractmethod
:By using ABC
as a base class, you signal that the class is intended to be abstract. The abstractmethod
decorator is crucial because it prevents the base class from being instantiated and forces subclasses to implement the abstract methods.
Purpose of Abstract Methods: Abstract methods define a template for what the subclasses should implement. This ensures that all subclasses provide specific implementations of the methods, making the code more predictable and easier to maintain.
Concrete Subclasses: Subclasses like Dog
and Fish
provide the actual functionality by implementing the abstract methods. If a subclass fails to implement any of the abstract methods, Python will raise an error, ensuring that the subclass cannot be instantiated unless it fully conforms to the abstract base class’s contract.
Error Handling: The code prevents the instantiation of the Animal
class directly, which enforces the rule that abstract classes are only blueprints for other classes and not meant to be used directly.
Using ABCs in Python encourages a clear and consistent design, especially when multiple developers or teams are working on different parts of a system that need to interact with each other.