Python OOP Encapsulation Explained ЁЯФР | Private, Protected & Public Variables

Encapsulation = protecting data inside a class.

✅ Object-Oriented Programming Part-2: Encapsulation ✍️

ЁЯФР What is Encapsulation

Encapsulation = protecting data inside a class.

Real-life example. ATM machine

  • You cannot access bank balance directly
  • You use functions (deposit, withdraw)

ЁЯФТ Why Encapsulation is important

  • Data security
  • Controlled access
  • Prevent accidental changes
  • Cleaner code structure

ЁЯУЪ Public Variables (Normal Variables)

Accessible from anywhere.

class Student:
    def __init__(self):
        self.name = "Deepak"
s = Student()
print(s.name)
Problem → anyone can change data.
s.name = "Ankit"
  

ЁЯФТ Protected Variables (_variable)

Single underscore → “internal use” warning.

class Student:
    def __init__(self):
        self._marks = 85
s = Student()
print(s._marks)
Rule → Use carefully outside class.
  

ЁЯФР Private Variables (__variable) ⭐

Double underscore → hidden from outside.

class Student:
    def __init__(self):
        self.__marks = 90
s = Student()
# print(s.__marks) # Error
Why error? Python hides it internally.
  

ЁЯФС Access Private Data using Methods (Getter & Setter)

Best practice.

Getter → read value

class Student:
    def __init__(self):
        self.__marks = 90

    def get_marks(self):
        return self.__marks

s = Student()
print(s.get_marks())
  

Setter → update value safely

class Student:
    def __init__(self):
        self.__marks = 0

    def set_marks(self, marks):
        if marks >= 0:
            self.__marks = marks

    def get_marks(self):
        return self.__marks

s = Student()
s.set_marks(85)
print(s.get_marks())
Now data is controlled.
  

ЁЯТ░ Real Example. Bank Account Protection

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

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

    def get_balance(self):
        return self.__balance

acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance())
User cannot directly change balance.
  

ЁЯУЭ Encapsulation Levels Summary

  • Public → name (fully accessible)
  • Protected → _name (internal use)
  • Private → __name (hidden)

ЁЯСЙ Practice Tasks for You

  1. Create class Employee with private salary
  2. Create class Bank with private balance and deposit method
  3. Create class Student with private marks and getter
  4. Create class Car with private speed and update method
  5. Prevent negative values using setter      python encapsulation

✅ Practice Task Solutions

Task 1. Create class Employee with private salary

class Employee:

    def __init__(self, salary):
        self.__salary = salary   # private variable

    def get_salary(self):
        return self.__salary

emp = Employee(50000)
print("Salary:", emp.get_salary())
  

Task 2. Create class Bank with private balance and deposit method

class Bank:

    def __init__(self, balance):
        self.__balance = balance

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

    def get_balance(self):
        return self.__balance

b = Bank(1000)
b.deposit(500)
print("Balance:", b.get_balance())
  

Task 3. Create class Student with private marks and getter

class Student:

    def __init__(self, marks):
        self.__marks = marks

    def get_marks(self):
        return self.__marks

s = Student(85)
print("Marks:", s.get_marks())
  

Task 4. Create class Car with private speed and update method

class Car:

    def __init__(self, speed):
        self.__speed = speed

    def update_speed(self, speed):
        if speed >= 0:
            self.__speed = speed

    def show_speed(self):
        print("Speed:", self.__speed)

c = Car(60)
c.update_speed(80)
c.show_speed()
  

Task 5. Prevent negative values using setter

class Product:

    def __init__(self, price):
        self.__price = 0
        self.set_price(price)

    def set_price(self, price):
        if price >= 0:
            self.__price = price
        else:
            print("Price cannot be negative")

    def get_price(self):
        return self.__price

p = Product(100)
p.set_price(-50)   # invalid
print("Price:", p.get_price())
  

ЁЯТб One-line memory rule
Encapsulation = hide data + control access.

рдЯिрдк्рдкрдгिрдпाँ

Top Quizzes

100 Hard Level UP GK & GS Quiz in Hindi 2026: рд╕рднी рд╕рд░рдХाрд░ी рдкрд░ीрдХ्рд╖ाрдУं рдХे рд▓िрдП рдорд╣рдд्рд╡рдкूрд░्рдг рдк्рд░рд╢्рди

Top 50 Pattern Programming Questions with Python Solutions

Interesting GK Questions (AI & Modern)

Complete Data Engineering Roadmap for Beginners (Step-by-Step Guide for Students)

Computer GK Questions in Hindi 2026 – SSC, Railway, UP Police Important MCQ

GK Question || GK In Hindi || GK Question and Answer || GK Quiz

UP GK Mock Test 2026: 100 qution рдЙрдд्рддрд░ рдк्рд░рджेрд╢ рд╕ाрдоाрди्рдп рдЬ्рдЮाрди рдорд╣рдд्рд╡рдкूрд░्рдг рдк्рд░рд╢्рдиोрдд्рддрд░ी