What is Encapsulation in Python?

Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It refers to wrapping data (variables) and methods (functions) into a single unit, i.e., a class. It helps in data hiding, which means restricting access to internal object details.


How to Implement Encapsulation in Python

Python doesn't have true private variables like some other languages, but it follows naming conventions to indicate the level of access:

  • _protected_var: Should not be accessed outside class (convention)
  • __private_var: Name mangled, makes it harder to access directly

Example: Encapsulation in Python

class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def get_balance(self):
        return self.__balance

acc = Account("John", 1000)
acc.deposit(500)
print(acc.get_balance())
# print(acc.__balance)  # This will raise AttributeError

Output:

1500

Benefits of Encapsulation

  • Protects data from unauthorized access
  • Helps in maintaining code structure
  • Increases security and modularity


What is Abstraction in Python?

Abstraction means hiding complex implementation details and showing only the essential features. It allows programmers to focus on what an object does, not how it does it.



How to Achieve Abstraction in Python

Python provides abstraction using the abc module (Abstract Base Classes).

Syntax:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

Example: Abstraction in Python

from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start_engine(self):
        pass

class Car(Vehicle):
    def start_engine(self):
        print("Car engine started")

class Bike(Vehicle):
    def start_engine(self):
        print("Bike engine started")

car = Car()
bike = Bike()
car.start_engine()
bike.start_engine()

Output:

Car engine started  
Bike engine started

Difference Between Encapsulation and Abstraction

Feature Encapsulation Abstraction
Definition Binds data and code together Hides complex details and shows essentials
Purpose Data hiding and protection Reduce complexity
Implementation Access modifiers, private/protected fields Abstract classes and methods (abc module)
Visibility Internal to the class Interface visible, internal hidden

Real-Life Analogy

Concept Example
Encapsulation Capsule with mixed medicine
Abstraction Car driving without knowing engine mechanics