Understanding Abstraction in Python: Data and Process Abstraction
Explore the concept of abstraction in Python, a fundamental principle of object-oriented programming. Learn how data and process abstraction help hide unnecessary details, reducing complexity and improving code efficiency.
Python - Abstraction
Abstraction is a key principle of object-oriented programming. It hides irrelevant details and exposes only essential data, reducing complexity and increasing efficiency.
Types of Abstraction
- Data Abstraction: Hides the original data entity via a data structure.
- Process Abstraction: Hides the implementation details of a process.
Abstract Class in Python
An abstract class cannot be instantiated but can be used as a base class. To create an abstract class, inherit from the ABC class in the abc module and include at least one abstract method decorated with @abstractmethod.
Example: Create an Abstract Class
from abc import ABC, abstractmethod
class Demo(ABC):
@abstractmethod
def method1(self):
print("abstract method")
def method2(self):
print("concrete method")
Instantiating an abstract class raises a TypeError
:
Output
TypeError: Can't instantiate abstract class Demo with abstract method method1
Abstract Method Overriding
The child class must override the abstract method. If not, Python throws a TypeError
:
Example: Override Abstract Method
from abc import ABC, abstractmethod
class DemoClass(ABC):
@abstractmethod
def method1(self):
print("abstract method")
def method2(self):
print("concrete method")
class ConcreteClass(DemoClass):
def method1(self):
super().method1()
obj = ConcreteClass()
obj.method1()
obj.method2()
Output
abstract method
concrete method