Defining Abstract Base Classes
Declaring Abstract Base Classes
To define an abstract base class in Python, you need to use the abc
module, which provides the necessary tools for creating and working with abstract classes. The key components are:
ABC
: The base class for creating abstract base classes.
@abstractmethod
: A decorator used to mark a method as abstract, which must be implemented by the subclasses.
Here's an example of how to declare an abstract base class:
from abc import ABC, abstractmethod
class MyAbstractClass(ABC):
@abstractmethod
def my_abstract_method(self, arg1, arg2):
"""This method must be implemented by subclasses."""
pass
def concrete_method(self):
"""This is a concrete method that can be used by subclasses."""
print("This is a concrete method.")
In this example, MyAbstractClass
is an abstract base class that defines an abstract method my_abstract_method()
. Any class that inherits from MyAbstractClass
must implement this method, or it will be considered an abstract class as well.
Implementing Subclasses
Subclasses of an abstract base class must implement all the abstract methods defined in the parent class. Here's an example:
class ConcreteClass(MyAbstractClass):
def my_abstract_method(self, arg1, arg2):
"""Implement the abstract method."""
print(f"Implementing my_abstract_method with args: {arg1}, {arg2}")
ConcreteClass
inherits from MyAbstractClass
and provides an implementation for the my_abstract_method()
.
Instantiating Abstract Base Classes
Since abstract base classes cannot be instantiated directly, you cannot create an instance of MyAbstractClass
. However, you can create an instance of ConcreteClass
, which is a subclass of MyAbstractClass
:
concrete_obj = ConcreteClass()
concrete_obj.my_abstract_method("hello", "world")
concrete_obj.concrete_method()
This will output:
Implementing my_abstract_method with args: hello, world
This is a concrete method.
By using abstract base classes, you can ensure that your subclasses implement the required methods and adhere to the expected behavior, leading to more robust and maintainable code.