Last Updated on August 7, 2024 by Abhishek Sharma
Abstraction is a fundamental concept in programming that helps in managing complexity by hiding the implementation details and exposing only the necessary parts of a functionality. In Python, abstraction allows developers to focus on what an object does rather than how it does it. This approach simplifies code management, enhances readability, and fosters reusable and maintainable code. This article explores the concept of abstraction in Python, its implementation, and its benefits.
Real World Example of Abstraction:-
For example, when we go to an ATM we can perform various tasks like withdrawing cash, checking balance, retrieving statements, changing a PIN, and many more so while performing these tasks we don’t know the internal implementation of the tasks. That’s how abstraction is useful when we want to show only the required information to the user while hiding other information.
Data Abstraction in Python:-
We can define an abstract method using @abstractmethod keyword on the top of a method. We can use abc module of python to achieve data abstraction in python. To define an abstract method in python we can import abstractmethod from the abc module of python. Let’s understand how to define data abstraction in python with help of an example.
# abstraction in python from abc import ABC,abstractmethod class Prepbytes(ABC): @abstractmethod def my_method(self): # body will always be empty Pass
In the above program, First, we import ABC (Abstract Base Class) and abstractmethod from the module abc. After that, we created a class Prepbytes which extends the class ABC and inside the class, we created a method my_method and we used the keyword @abstractmethod on top of the method to define it as an abstract method.
Data Abstraction in Python:-
Let’s understand how we can use the inbuild python class Abstract Base Class (ABC) to achieve data abstraction in python. We can say a class is an abstract class when a class contains an abstract method. We can use @abstractmethod keyword to define an abstract method in python. Let’s understand what is data abstraction in python with help of an example.
# abstraction in python from abc import ABC,abstractmethod # abstract class class Subject(ABC): @abstractmethod def subject(self): pass class Maths(Subject): # override superclass method def subject(self): print("Subject is Maths") class Physics(Subject): # override superclass method def subject(self): print("Subject is Physics") class Chemistry(Subject): # override superclass method def subject(self): print("Subject is Chemistry") class English(Subject): # override superclass method def subject(self): print("Subject is English") maths=Maths() maths.subject() physics=Physics() physics.subject() chemistry=Chemistry() chemistry.subject() english=English() english.subject()
Output:-
Subject is Maths
Subject is Physics
Subject is Chemistry
Subject is English
In the above python program, we created an abstract class Subject which extends Abstract Base Class (ABC). We also defined an abstract method subject. We also created other classes like Maths, Physics, Chemistry, and English which all extend an abstract class Subject thus all these classes are subclasses and the Subject is the superclass. We provided different implementations for the subject method of all the subclasses.
Abstract Class in Python:-
An abstract class is a class that contains both abstract and concrete (normal) methods. Let’s see an example of how an abstract class looks in python.
import abc from abc import ABC, abstractmethod class Prepbytes(ABC): # an abstract method @abstractmethod def abstract_method(self): print("The abstract method") # a normal method def normal_method(self): print("The normal method")
In the above program, we created an abstract class in that we created an abstract method and a normal method. We can implement the abstract method in the subclass and we can call the normal method directly.
We can not directly create an object of an abstract class because an abstract class may contain an abstract method and implementation of an abstract method is not given. Let’s try to understand this with help of an example.
import abc from abc import ABC, abstractmethod class Color(ABC): # an abstract method @abstractmethod def print_color(self): pass class Red(Color): def print_color(self): print("The Color is red") class Green(Color): def print_color(self): print("The Color is green") class Blue(Color): def print_color(self): print("The Color is blue") # trying to create an object of an abstract class obj=Color()
Output:-
Traceback (most recent call last):
File "", line 15, in
TypeError: Can't instantiate abstract class Prepbytes with abstract methods abstract_method
In the above program, we created an abstract class Color. We try to create an object of the class Color but as an abstract class may contain an abstract method the program will throw an error.
What are Concrete Methods in Abstract Base Class(ABC)?
If a class contains only concrete methods ( normal methods) we can say it is a concrete class. On the other hand, an abstract class contains both normal and abstract methods. The concrete class is mainly used to provide an implementation of the abstract methods of the abstract superclass. Let’s see an example to understand how to use concrete class.
import abc from abc import ABC, abstractmethod class SuperClass(ABC): @abstractmethod def my_method(self): print("The abstract superclass") class SubClass(SuperClass): def my_method(self): super().my_method() print("The subclass") obj=SubClass() obj.my_method()
Output:-
The abstract superclass
The subclass
In the above program, we created an abstract class SuperClass with an abstract method my_method. We also created a concrete class SubClass in that we created a normal method my_method which overrides the superclass method we also called super class method using the super() method in a subclass.
Abstract Properties of an Abstract Class:-
An abstract base class of python also provides the functionality of abstract properties along with abstractmethod. We can use the @abstractproperty decorator of the abc module to achieve abstract properties. Abstract properties are generally used to achieve getters and setters functionality.
import abc from abc import ABC, abstractmethod class Color(ABC): def __init__(self,color): self.color=color # an abstract method @abc.abstractproperty def print_color(self): pass class Red(Color): def __init__(self): super().__init__("Red") @property def print_color(self): return self.color class Green(Color): def __init__(self): super().__init__("Green") @property def print_color(self): return self.color class Blue(Color): def __init__(self): super().__init__("Blue") @property def print_color(self): return self.color obj=Green() print("The color is "+obj.color)
Output:-
The color is Green
In the above program, we created an abstract class Color and created a method print_color method with a keyword @abstractproperty and we also created a constructor to initialize the color variable. We also created subclasses like Red, Green, and Blue which extend an abstract class Color. We implemented a method print_color in every subclass to assign a color of the variable color. On top of every method of the subclass, we set a keyword @property. When we create an object of the subclass first of all constructor of the subclass is called and it set the initial value of the variable color. In the above example, we created an object (obj) of subclass Green so the first constructor of the Green class is called and it set the initial value of color as “Green”. So when we print variable color (obj.color) it will return “Green”.
Conclusion
Abstraction is a powerful concept in Python that helps in managing complexity by exposing only the essential details and hiding the implementation specifics. It is a core principle of object-oriented programming that promotes simplified code management, enhanced readability, reusability, and maintainability. By using abstract classes, methods, and encapsulation, developers can build robust and scalable applications.
FAQs related to Abstraction in Python
Below are some FAQs related to Abstraction in Python:
1. What is abstraction in Python?
Abstraction in Python is a technique used to hide the internal implementation details of objects and expose only the necessary functionalities. It helps in managing complexity and building more manageable and maintainable code.
2. How do you create an abstract class in Python?
You can create an abstract class in Python using the abc module. An abstract class is defined by inheriting from ABC and declaring abstract methods using the @abstractmethod decorator.
3. What is the difference between abstraction and encapsulation?
Abstraction focuses on hiding the implementation details and exposing only the essential functionalities. Encapsulation, on the other hand, involves bundling data and methods within a class and restricting access to the inner workings. Both concepts are fundamental to object-oriented programming and often work together.
4. Can an abstract class be instantiated in Python?
No, an abstract class cannot be instantiated. It serves as a blueprint for other classes, and only its subclasses that implement the abstract methods can be instantiated.
5. Why is abstraction important in programming?
Abstraction is important because it simplifies code management, enhances readability, promotes code reusability, and makes maintenance easier. By focusing on what an object does rather than how it does it, abstraction helps in building complex systems in a more organized and manageable way.