Abstraction in Python

Abstraction in Python

5 mins read2.7K Views Comment
clickHere
Updated on Nov 22, 2022 19:25 IST

In this article, we will discuss abstraction in python and how to implement abstraction using abstract classes and methods.

2022_07_MicrosoftTeams-image-21.jpg

Python is an object-oriented programming language with classes and objects. In this article, we will focus on one of the most powerful OOPs concepts – Abstraction. We will learn how you can use Python to implement the abstraction.

We will be covering the following sections today:

What is Abstraction?

Abstraction refers to the process of hiding the details and showcasing essential information to the user. This is one of the core concepts of the object-oriented programming paradigm. Let’s understand abstraction with the help of an analogy.

Consider a building, for example, outside your window. You can see the outer structure of the building – the windows, the color, etc. But the number of rooms or the layout of the rooms inside it is not visible to you because these details are abstracted.

Now, let’s also look at a similar industrial use case –

Suppose you have subscribed to Netflix. So, as a user, all you have to do is sign-up and start interacting with the user interface of the platform. You can select the movie that you want to watch. However, we are not aware of what goes on in the backend – information such as how many movies are stored in their database, or how the data is being used to recommend movies to you. These details are not relevant to the users in general and so are hidden from them. This is another example of abstraction!

Now that we understand the concept of abstraction, let’s see how this feature is implemented in Python.

Must Read: What is Python?

Must Check: Python Online Course & Certification

Abstraction in Python

In Python, abstraction is achieved by using abstract classes and methods.

What are abstract classes and methods?

Just as a class is a user-defined blueprint for creating objects, an abstract class is a blueprint for creating other classes. Any class is referred to as an abstract class if it contains one or more abstract methods. An abstract method is a function that has a declaration but does not have any implementation.

These abstract classes are used when we want to provide a common interface for different implementations of a component. 

Why use abstract classes?

When an abstract class is defined, you are basically defining a common API for different sub-classes. This is especially useful when a third-party implements it. For example, the plugins, which provides customization for each user based on their need. 

Another important use case of abstract classes is when you are working with a larger team in the backend and remembering all the class names is next to impossible.

Working with abstract classes

Python does not provide abstract classes by default. To create abstract classes and perform abstraction, we need to first import the Python module abc. 

This abc module provides the infrastructure for defining the abstract base class in Python. Using this, we can define a structure, but there’s no need to provide complete implementation for every method.

 
from abc import ABC
class AbstractClassName(ABC):
Copy code

To define an abstract method, you use the @abstractmethod decorator:

 
from abc import ABC, abstractmethod
class AbstractClassName(ABC):
@abstractmethod
def abstract_method_name(self):
#Empty body
pass
Copy code

The methods whose definition would change as per different class/subclass is known as abstract class. You need to define its implementation while redefining it in the subclass.

But there might be some methods that have the same implementation for all the subclasses as well. Some features use the properties of the abstract class, so they must be implemented in the abstract class itself. Otherwise, it will lead to repetitive code in all the inherited classes. These types of methods are known as concrete methods.

 
from abc import ABC, abstractmethod
class Parent(ABC):
#common function
def common_fn(self):
print('Inside the common method of Parent Class')
@abstractmethod
def abs_fn(self): #is supposed to have different implementation in child classes
pass
class Child1(Parent):
def abs_fn(self): #concrete methods
print('Inside the abstract method of Child1')
class Child2(Parent):
def abs_fn(self): #concrete methods
print('Inside the abstract method of Child2')
Copy code

NOTE: An abstract class can have both abstract methods and concrete methods. You can access both methods by instantiating the object of the abstract class. 

Points to remember:

  • Always provide an implementation of the abstract method in the child class even when implementation is given in the abstract class.
  • A subclass must implement all abstract methods defined in the parent class otherwise it results in an error.

Let’s take an example where we have a class Animal as the parent class and other child classes that are derived from it:

2022_07_image-160.jpg
 
from abc import ABC,abstractmethod
class Animal(ABC):
#concrete method
def sleep(self):
print("Going to sleep in a while")
#concrete method
def eat(self):
print("Start eating")
@abstractmethod
def sound(self):
print("This function for defining the sound of any animal")
pass
class Snake(Animal):
def sound(self):
print("I hiss")
class Dog(Animal):
def sound(self):
print("I bark")
class Lion(Animal):
def sound(self):
print("I roar")
Copy code

The above abstract parent class has sleep() and eat() as the concrete methods. These methods will remain the same for all the child classes. We are not defining these methods as abstract methods as we don’t want to write the same statement repeatedly. But we are defining the sound() as an abstract method because different animals make different sounds and we would have to define it for each animal in their respective child class. 

Let’s try to access the concrete and abstract methods by instantiating the child class object.

 
l = Lion()
l.sleep()
l.sound()
s = Snake()
s.sound()
Copy code

Output:

2022_07_image-161.jpg

Now, if you want to invoke the sound() function from the parent class directly, we can use the object of the child class, but we would have to invoke it through the super keyword.

 
class Cat(Animal):
def sound(self):
super().sound()
print("I meow")
c = Cat()
c.sound()
Copy code

Output:

2022_07_image-162.jpg

NOTE: If we do not provide any implementation of the abstract method in the child class, it will result in an error. 

For example, not providing the implementation of the sound() function in the child class will result in an error. 

 
class Deer(Animal):
def sound(self):
pass
c = Deer()
c.sound()
c.sleep()
Copy code

Output:

2022_07_image-163.jpg

NOTE: If you have more than one abstract method in the parent class, make sure to implement each of them in the base class, or else it will result in the same error.

Conclusion

Hope this article was helpful for you to understand abstraction in python and how to implement abstraction using abstract classes and methods. The OOPs concepts are among the interviewer-favorite topics for Python-related roles. If you wish to learn more about Python and practice Python programming, you can explore related articles here.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments