Abstract Classes in Python

Abstract Classes in Python

Image for postPhoto by Photo Boards on Unsplash


Abstract Class is a very important concept of object-oriented programming. It is a good practice of DRY (Don?t Repeat Yourself) principle. In a large project, code duplication is approximately equal to bug reuse and one developer is impossible to remember all classes? details. Therefore, it?s very helpful to use an abstract class to define a common interface for different implementations.

An abstract class has some features, as follows:

  • An abstract class doesn?t contain all of the method implementations required to work completely, which means it contains one or more abstract methods. An abstract method is a method that just has a declaration but does not have a detail implementation.
  • An abstract class cannot be instantiated. It just provides an interface for subclasses to avoid code duplication. It makes no sense to instantiate an abstract class.
  • A derived subclass must implement the abstract methods to create a concrete class that fits the interface defined by the abstract class. Therefore it cannot be instantiated unless all of its abstract methods are overridden.

In a nutshell, an abstract class defines a common interface for a set of subclasses. It provides common attributes and methods for all subclasses to reduce code duplication. It also enforces subclasses to implement abstract methods to avoid odd inconsistencies.

Define Abstract Class in Python

Python comes with a module called abc which provides useful stuff for abstract class.

We can define a class as an abstract class by abc.ABC and define a method as an abstract method by abc.abstractmethod. ABC is the abbreviation of abstract base class.

Note: A class is not real abstract if it has abstract methods but not inherit from abc.ABC, which means it can be instantiated. For example:

Invoke Methods from Abstract Classes

Actually an abstract method is not needed to be ?totally abstract? in Python, which is different with some other object-oriented programming language. We can define some common stuff in an abstract method and use super() to invoke it in subclasses.

As above example shown, the move abstract method can contain some functions and can be invoked by subclass using super(). Although it have a little implementation, it is still a abstract method and we have to implement it completely in subclasses.

Image for postPhoto by Alexander Schimmeck on Unsplash

Thanks for reading. If you like it, please follow my publication TechToFreedom, where you can enjoy other Python tutorials and topics about programming, technology and investment.


No Responses

Write a response