Abstract Classes
Abstract Classes in Python
Concept and Purpose
An abstract class is a class that is designed to be inherited from, but not instantiated directly. It often contains one or more abstract methods - methods that are declared, but don’t have an implementation in the abstract class.
Key characteristics:
- Cannot be instantiated directly
- May contain abstract methods (methods without a body)
- May contain concrete methods (methods with an implementation)
- Subclasses must implement all abstract methods
Purpose:
- To define a common interface for a set of subclasses
- To enforce certain methods to be implemented by subclasses
- To share code among several closely related classes
Abstract Base Classes (ABC) in Python
Python provides the abc
module to work with abstract base classes.
Basic Usage:
In this example: - Animal
is an abstract base class - make_sound
is an abstract method - move
is a concrete method
Implementing an Abstract Class:
Key Points:
- The
@abstractmethod
decorator marks a method as abstract - Subclasses must implement all abstract methods
- Abstract classes can have both abstract and concrete methods
- Trying to instantiate an abstract class directly will raise a
TypeError
Why Use Abstract Classes?
Enforcing a common interface: Abstract classes ensure that all subclasses implement certain methods, guaranteeing a common interface.
Code reuse: You can implement common functionality in the abstract base class, which all subclasses can use.
Designing frameworks: Abstract classes are useful when designing large frameworks where you want to provide default behaviors but require specific implementations in subclasses.
Example: Shape Hierarchy
Here’s a more practical example using shapes:
In this example, Shape
is an abstract base class that defines the common interface for all shapes. Circle
and Rectangle
are concrete implementations of Shape
.
Conclusion
Abstract base classes in Python provide a powerful way to define interfaces and ensure that derived classes implement certain methods. They’re useful for creating frameworks and libraries, ensuring consistency across related classes, and defining clear contracts for subclasses to follow.
By using abstract classes, you can create more robust and well-structured code, especially when dealing with complex hierarchies of related classes.