Abstraction in Python

Abstraction in Python

Abstraction is a fundamental characteristic of object-oriented programming (OOP), which helps us understand objects more simply by hiding irrelevant details and showing only relevant features. The abstraction concept is used when you have to make sure that child classes follow a pattern. In this blog, you will learn in detail what abstraction means in Python, how we can implement abstraction in Python using the ABC module and @abstractmethod decorator, and the benefits of abstraction.

Table of Contents:

Understanding Object-Oriented Programming (OOP) in Python

Let us assume you are building a system to manage different types of vehicles. You have cars, bikes, trucks, and buses. All the different vehicles have a few things in common, like brand, model, speed, and fuel capacity. Most of the vehicles also have some unique features to them. For example, cars may provide air conditioning, trucks may provide load capacity, and bikes may provide helmet storage.

If you had to write this all out without OOP, you would have to write out a different section of code to create each different vehicle. You would also have to write the same duplicated code for the properties that they all share. This would make your code messy, repetitive, and impossible to manage.

Object-Oriented Programming (OOP) provides an easy, scalable solution to this.

With OOP, you can write structured, reusable blocks of code that reflect real-world objects like a Car, a Bike, or a Truck. These objects can inherit their shared features from a base class called Vehicle, but still be unique in their behaviour. This will reduce the size of the code, and it will help make your code organised, readable, and easier to maintain.

Object-Oriented Programming in Python is built on four key principles, often referred to as the four pillars of OOP:

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
Object-Oriented Programming

In this article, you will learn how to implement abstraction in modules and systems. We will take the Vehicle Management system as an example and implement it in Python.

Master Python with Real-World Projects – Enroll Today!
Build job-ready skills with practical examples and expert guidance.
quiz-icon

What is Abstraction in Python?

Abstraction refers to the concept of hiding unnecessary implementation details. This helps reduce complexity by exposing only necessary parts and hiding the internal logic from users.

Take driving a car as an example. The driver of a car needs to know how to use the brake function. The details of how the braking system works, whether it is hydraulics, brake pads, or some other electrical mechanism, is not something the driver should be concerned about. The driver should only focus on driving. 

Let us consider a digital example. Let’s say you are using Twitter. You will just be concerned with composing and posting a tweet. You don’t care about how the app makes the POST request behind the scenes, what the data does after the API call, or how your tweet is encrypted and stored in the database. The developers can use abstraction to provide users with a simple interface while hiding the many details working behind the scenes.

This is abstraction. In abstraction, you work with a simplified interface, and the complex workings are hidden behind the scenes.

Example:

Python

Output:

Abstraction in Python - Output 1

Explanation: In this code example, Vehicle is an abstract class that defines the start_engine() method without specifying how it works. child classes like Car implement the actual behaviour, hiding internal details from the user.

Implementing Abstraction in Python with Example

Abstraction in Python is mainly accomplished by using the ABCs (Abstract Base Classes) module. The abc module allows you to define abstract classes, which lay out a common blueprint for all the derived classes, and can also have abstract methods. These methods can be declared without implementation.

After defining abstract base classes, we use the @abstractmethod decorator, which ensures that a child class must implement all the abstract methods. This generates cleaner and more organised code that is scalable as well.

Let us look at both of these steps in detail.

Step 1: Defining Abstract Class Using ABC Module in Python

To create an abstract class in Python, you import an abstract base class from the abc module. An abstract class is a template class that cannot be directly instantiated. It usually has one or more abstract methods, which must be implemented by any derived classes.

Note: While Python lacks a formal interface type like Java or C#, developers simulate interfaces using Abstract Base Classes (ABCs). An ABC can act like an interface if it contains only abstract methods, or like a partially implemented superclass if it contains a mix of abstract and concrete methods. This flexibility is a unique feature of Python’s abstraction system.

Example:

Python

Output:

Step 1: Defining Abstract Class Using ABC Module in Python

Explanation: Here, Vehicle is an abstract base class that defines a blueprint without providing any specific implementation. The Car class inherits from Vehicle and implements the drive() method.

Note: At this stage, Vehicle is abstract in structure but doesn’t enforce any method implementation yet. That comes in the next step.

Step 2: Enforcing Method Implementation Using @abstractmethod

After creating an abstract class using the ABC module, you can define abstract methods using the @abstractmethod decorator. It is not mandatory to include abstract methods. If no abstract methods are defined, the class can still be created and used like a normal class.

This decorator enforces a rule: Any child class that inherits from the abstract base class must implement all abstract methods. Otherwise, attempting to instantiate the child class will raise a TypeError.

Important: You cannot instantiate an abstract class that contains unimplemented abstract methods. Attempting to do so will raise a TypeError.

This is how @abstractmethod “enforces” the presence of abstract methods and ensures that all derived classes follow a consistent structure and fulfil the contract defined by the abstract class. This is how abstraction is implemented in Python by creating a clear blueprint that the child classes are required to follow.

Note: Child classes can override concrete methods too if a different behaviour is needed.

Example:

Python

Output:

Step 2: Enforcing Method Implementation Using @abstractmethod

Explanation: In this case, trying to instantiate the Bike class, which has not implemented the start_engine() abstract method, resulted in a TypeError. The Car class had the method implemented, so it does not raise an error. This is how @abstractmethod requires the child classes to comply with the specifications of the abstract base class.

Advanced Abstraction in Python

While most abstract methods are instance-based, Python also supports abstract class methods and static methods using a combination of decorators. Because of this feature, abstract base classes can define methods that don’t need to use any information from a specific object (self) or even from the class itself (cls).

This is particularly helpful for:

  • Utility Functions (e.g., validation functions).
  • procedures for class-level setup or setting.

Get 100% Hike!

Master Most in Demand Skills Now!

Using @abstractmethod with @classmethod in Python

To declare a class method as abstract, combine the @classmethod decorator with @abstractmethod. Make sure @abstractmethod comes after @classmethod.

Example:

Python

Output:

Using @abstractmethod with @classmethod

Explanation: The Logger class is abstract and enforces that every subclass must define a configure method that operates at the class level using cls. FileLogger does exactly that, so calling configure() on it works without error and prints the settings. 

Using @abstractmethod with @staticmethod in Python

A static method is a function that belongs to a class, but doesn’t need to know anything about the specific instance (self) or the class itself (cls). You can declare a static method that is abstract using @staticmethod along with @abstractmethod.

Why Make a Static Method Abstract?

Sometimes, in a blueprint class (i.e., an abstract class), you want to force child classes to implement a certain method, even if that method doesn’t use self or cls.

Example:

Python

Output:

Using @abstractmethod with @staticmethod

Explanation: The Validator class defines an abstract static method, validate, which must be implemented by all subclasses. EmailValidator provides the actual logic, and the method can be called directly without creating an object.

Understanding Concrete Methods in Abstract Class in Python

Abstract classes can have concrete methods in addition to abstract methods, which are methods that are fully defined within the abstract class. Concrete methods allow abstract classes to provide default behaviour that child classes can inherit, reducing redundancy and promoting code reuse. Concrete methods define default behaviour while allowing child classes to define behaviour wherever they need to behave differently.

Note: a class can have only concrete methods and still be “abstract” if it contains an @abstractmethod anywhere.

Example:

Python

Output:

Concrete Methods in Abstract Class in Python

Explanation: The stop_engine() method was automatically inherited by the Car class. It was fully defined, which is an example of concrete method. 

Since every vehicle must have a stop_engine() functionality, the developer included it as a concrete method in the abstract class itself. This ensures that all the child classes inherit this behaviour by default, preventing mistakes where another developer might forget to implement it manually.

Understanding Abstract Properties in Python

Although Python does not directly support abstract instance variables, it allows you to define abstract properties using @property and @abstractmethod. This is helpful when you want to enforce that a derived class must define a certain property.

Example:

Python

Output:

Understanding Abstract Properties in Python

Explanation: The code above outputs Canine because the Dog class implements the abstract species property from the Animal abstract base class. When the d.species is called, it returns the string “Canine”.

Top Benefits of Abstraction in Python Programming

Abstraction is a powerful tool that reduces the complexity of a problem since it allows us to create simpler representations of systems that may involve complexity. Abstraction helps us focus on what a function does, without worrying about how it works behind the scenes. Hence, using abstraction will give you cleaner, better-organised code and fewer errors.

The following are some of the main benefits of using abstraction in Python: 

  • Readability and maintainability: If an abstract class is used, it hides unnecessary details, making the code easier to read or maintain. Developers can write code with a high-level structure without being distracted by what is implemented inside. 
  • Reusability: Using abstract classes and methods gives you a reusable blueprint. This way, you can create multiple child classes and share behaviour with the child classes. The child classes can still implement their custom logic. 
  • Consistency: By using @abstractmethod, the abstract class makes sure that all the child classes implement the critical methods. This ensures correctness since now a user cannot accidentally miss implementing the compulsory functions. It also creates consistency in the design of your code. This is especially beneficial in game development.
  • Better collaboration in teams: In large projects, abstraction helps improve collaboration on teams. For example, one team could work on the abstract class, the interface, while the other team works independently on implementing the concrete child classes.
  • Encourages Design Discipline: Abstraction encourages designing around interfaces and responsibilities rather than specific class implementations. This will lead to better architectural decisions that are more thought out, scalable, and have a long-term future.

Real World Example Using Python

For a better understanding of abstraction in Python, let us try and model a payment system that supports multiple payment methods — credit card, PayPal, and cryptocurrency.

You can define an abstract class PaymentProcessor that requires a pay method:

Code: 

Python

Output:

Real World Example Using Python

Explanation: This example shows how abstraction can provide a clean interface (pay) while allowing different payment methods to implement their logic, which is crucial for extensibility.

Start Coding in Python – Absolutely Free
Learn Python fundamentals step-by-step through interactive lessons and real projects.
quiz-icon

Conclusion

Abstraction is one of the core pillars of object-oriented programming, which is used to simplify the complexity of the code by showing only the necessary details and hiding everything else. Abstraction in Python can be done using the abc module. You can define abstract methods with the @abstractmethod decorator. Abstraction will organise your code by adding common behaviour into base classes that all the child classes must implement. Learning to utilise abstraction fully will not only clean up your code but will also support better design, collaboration, and maintenance. 

To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

Abstraction in Python – FAQs

Q1. What is the distinction between an abstract class and an interface in Python?

An abstract class can have both abstract methods and concrete methods, while an interface only defines abstract methods and no implementation.

Q2. Can an abstract class have a constructor in Python?

Yes, abstract classes can have constructors to initialise common attributes for their child classes.

Q3. What would happen if I did not implement all the abstract methods in a child class?

If you do not implement all the abstract methods in a child class, Python will raise a TypeError.

Q4. Can abstract classes have instance variables?

Yes, abstract classes can define and use instance variables.

Q5. When should I use abstraction in Python and what are its benefits?

Abstraction should be used when you want to hide complex logic, making your code more modular, easier to maintain, and flexible for future changes.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner