Beginner's guide to abstract base class in Python
Hatched by Alexandr
May 13, 2024
3 min read
14 views
Beginner's guide to abstract base class in Python
Abstract base classes (ABCs) provide a blueprint for other classes in Python. They don't contain the implementation but rather provide an interface that ensures derived classes are properly implemented. The use of ABCs helps make code more maintainable and programmer-friendly. In this article, we will explore the concept of abstract base classes in Python and how they can be implemented.
To understand the need for abstract base classes, let's consider an example of creating a game with different animals. We can define an abstract class called Animal, from which classes like Dog, Cat, and Duck can be derived. The Animal class will have methods like get_age() and is_dead() that every animal should implement. This ensures that every animal class derived from the Animal base class supports these methods.
There are two important rules to follow when using abstract base classes. Rule 1 states that subclasses inherited from a specific base class must implement all the methods and properties defined in the abstract base class. Rule 2 states that abstract base classes cannot be instantiated; they are inherited by other subclasses.
Let's implement the animal classes in Python according to these rules:
class Animal:
def get_age(self):
raise NotImplementedError()
def is_dead(self):
raise NotImplementedError()
class Dog(Animal):
def bark(self):
print("woof woof!")
def get_age(self):
print("5 years")
In the above code, the Dog class inherits all the methods from the Animal class. We can test if Rule 1 is followed by creating an object of the Dog class and calling the methods:
bulldog = Dog()
bulldog.get_age() Output: 5 years
bulldog.is_dead() Output: NotImplementedError
As expected, the subclass Dog does not implement the is_dead method from the Animal base class, resulting in a NotImplementedError when calling the method. However, the program can still run without any warnings, even though it breaks Rule 1. Ideally, all methods of the base class should be implemented by the subclass.
To enforce both Rule 1 and Rule 2, we can use Python's abc module. Let's update the code to use the abc module:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def get_age(self):
pass
@abstractmethod
def is_dead(self):
pass
class Dog(Animal):
def bark(self):
print("woof woof!")
def get_age(self):
print("5 years")
In this updated code, we import the helper class ABC from the abc module and use the decorator @abstractmethod for all the methods in the base class. Now, let's test if both rules are followed:
bulldog = Dog() Output: TypeError: Can't instantiate abstract class Dog with abstract methods is_dead
This time, we get a TypeError specifying that the abstract method is not implemented, following Rule 1. Additionally, let's try to instantiate the base class:
animal = Animal() Output: TypeError: Can't instantiate abstract class Animal with abstract methods get_age, is_dead
Again, we get a TypeError stating that the abstract class cannot be instantiated, following Rule 2.
In conclusion, using abstract base classes in Python can make class hierarchies more robust and maintainable. By enforcing the implementation of specific methods in derived classes and preventing the instantiation of abstract base classes, ABCs help create bug-free and readable code.
Actionable Advice:
- When designing class hierarchies in Python, consider using abstract base classes to enforce method implementation and prevent instantiation of base classes.
- Use the abc module and the ABC helper class to define abstract base classes and the @abstractmethod decorator to mark methods that must be implemented by subclasses.
- Test your code to ensure that both Rule 1 (method implementation) and Rule 2 (no instantiation of base classes) are followed.
By following these guidelines, you can create more maintainable and programmer-friendly code in Python.
Sources
Hatch New Ideas with Glasp AI 🐣
Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)
Start Hatching 🐣