Abstraction & Encapsulation¶
1. Encapsulation¶
Encapsulation is the process of wrapping data and the methods that work on data within a single unit. It acts as a protective shield that prevents the data from being accessed by the code outside this shield.
In Python, we achieve encapsulation by using private members (indicated by a double underscore __).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
2. Abstraction¶
Abstraction is used to hide the internal details and show only the functionalities.
In Python, we can achieve abstraction by using Abstract Classes and methods. We use the abc module for this.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
The Difference
- Encapsulation: "I will hide my data so you can't touch it directly." (Focus on Security)
- Abstraction: "I will hide the complex details so you only see the simple interface." (Focus on Design)