Python tutorials > Object-Oriented Programming (OOP) > Inheritance > What are abstract base classes?
What are abstract base classes?
Abstract Base Classes (ABCs) are classes that cannot be instantiated directly. They serve as blueprints for other classes, defining a set of methods that subclasses must implement. ABCs enforce a specific interface, ensuring that derived classes adhere to a contract. This is a powerful tool for code organization and maintainability, especially in large projects. In Python, ABCs are defined using the abc
module. The ABCMeta
metaclass is used to create abstract classes, and the @abstractmethod
decorator is used to declare abstract methods.
Basic Example of an Abstract Base Class
This example demonstrates a simple abstract base class called The Shape
. It defines two abstract methods: area
and perimeter
. Any class that inherits from Shape
must implement these methods. If a subclass fails to implement any of the abstract methods, attempting to instantiate that subclass will raise a TypeError
.Square
class inherits from Shape
and provides concrete implementations for area
and perimeter
.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
def perimeter(self):
return 4 * self.side
# Attempting to instantiate Shape directly will raise a TypeError
# shape = Shape()
square = Square(5)
print(f"Area of square: {square.area()}")
print(f"Perimeter of square: {square.perimeter()}")
Concepts Behind the Snippet
The key concepts are:
Real-Life Use Case
Consider a framework for processing different types of documents (e.g., PDF, Word, CSV). An abstract base class This ensures that all document processors adhere to a consistent interface, making it easier to switch between different processors or add new ones without breaking the code.DocumentProcessor
could define abstract methods like load_document
, extract_text
, and save_document
. Concrete classes like PDFProcessor
, WordProcessor
, and CSVProcessor
would then inherit from DocumentProcessor
and implement these methods according to the specific document format.
Best Practices
Here are some best practices for using ABCs:
@abstractproperty
for abstract properties that subclasses must define.
Interview Tip
When discussing ABCs in an interview, emphasize their role in enforcing contracts and promoting code reuse. Be prepared to explain how ABCs relate to the principles of abstraction, inheritance, and polymorphism. Provide concrete examples of how ABCs can be used to solve real-world problems. A good answer should demonstrate an understanding of when to use ABCs, and why they are preferred over alternatives like informal interfaces (relying solely on documentation).
When to Use Them
Use ABCs when:
Memory Footprint
ABCs themselves do not significantly increase memory footprint. The primary memory impact comes from the objects created from the concrete subclasses that inherit from the ABC. The size of these objects depends on the data they hold and the methods they implement.
Alternatives
Alternatives to ABCs include:
Pros
Cons
FAQ
-
Can I instantiate an abstract base class directly?
No, you cannot instantiate an abstract base class directly. Attempting to do so will raise aTypeError
. -
What happens if a subclass doesn't implement all abstract methods?
If a subclass doesn't implement all abstract methods, it becomes an abstract class itself, and you cannot instantiate it. Attempting to instantiate it will also raise aTypeError
. -
How do I define an abstract property?
You can define an abstract property using the@abstractproperty
decorator in conjunction with theproperty
function or the@property
decorator. For example: python from abc import ABC, abstractproperty class MyAbstractClass(ABC): @abstractproperty def my_property(self): pass