Abstract Class in Python — A Complete Guide (with Examples)

An abstract method is a method that has a declaration but no implementation. A Python class with at least one abstract method is called an abstract class.

To create an abstract class in Python, use the abc module.

For example, here is an abstract class Pet:

from abc import ABC, abstractmethod

class Pet(ABC):
   @abstractmethod
   def makesound(self):
      pass

The idea of an abstract class is that when you inherit it, the child class should define all the abstract methods present in the parent class.

Notice that you cannot create objects of an abstract class. An abstract class can only act as a blueprint for creating subclasses.

Why Abstract Classes?

An abstract class acts as a blueprint for subclasses. It is the main class that specifies how the child classes should behave. In a sense, an abstract class is the “class for creating classes”.

For example, Shape could be an abstract class that implements an abstract method area(). Then the subclasses Circle, Triangle, and Rectangle provide their own implementations of this method based on their characteristics in geometry.

So, abstract classes make it possible to enforce rules for creating related child classes.

How to Write Abstract Classes in Python

To write an abstract class in Python, you need to use the abc (Abstract Base Class) module.

Here’s how you can do it:

  1. Import ABC class and abstractmethod decorator from the abc module.
  2. Make your abstract class a subclass of the ABC class. This tells Python interpreter that the class is going to be an abstract class.
  3. Tag a method with the @abstractmethod decorator to make it an abstract method.

Now that you’ve learned how to build an abstract class in Python, let’s see some examples to make any sense of it.

Example: Creating Abstract Class in Python

In this example, we implement an abstract base class Pet. In this class, we implement an abstract method makesound().

Because different pets make different sounds, it makes sense to use an abstract class with an abstract makesound() method. This way, it is up to the pet type how to implement the makesound() method. All we care about is that the subclass must implement some version of the makesound() method.

Here’s an example code that uses the abstract Pet class in creating a Cat subclass to represent cats:

from abc import abstractmethod

class Pet():
   @abstractmethod
   def makesound(self):
      pass

class Cat(Pet):
   def __init__(self, name):
       self.name = name

   def makesound(self):
      return "Meow!"

cat = Cat("Max")
print (f"I like to say {cat.makesound()}")

Output:

I like to say Meow!

At this point, you can verify that it is not possible to create an object from the abstract class!

For example:

pet = Pet()

Trying to create an object from the abstract class gives an error:

TypeError: Can't instantiate abstract class Pet with abstract method makesound

The error says it all. It’s not possible to create an abstract class object.

When Should I Use an Abstract Class in Python?

Some notable reasons as to why or when you should use an abstract class in Python include:

  • Avoids duplicate code.
  • Enforces consistency in how to implement subclasses.
  • Makes sure no critical methods and properties are forgotten subclasses.

These benefits are especially noticeable when working in a team of developers where the team members might reuse or extend your code. Enforcing strict rules for subclasses makes it easy to reuse and extend the code.

Conclusion

Today you learned what is an abstract class in Python.

To recap, an abstract class is “the class of classes”. It is a base class that specifies what methods its subclasses should implement. Abstract classes allow for specifying strict rules for how to write classes in Python. This helps write consistent and manageable code.

You cannot create an object from an abstract class.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading