๐น What is Encapsulation?
- Encapsulation means hiding data and keeping it safe.
- In Python, we use class to keep variables and functions together.
- It helps to protect the data from being changed accidentally.
๐ Think of a capsule โ it keeps medicine safely inside.
Encapsulation keeps data and code safely inside the class.
๐น Why Encapsulation?
โ
Easy to use
โ
Protects data
โ
Only allow limited access
โ
Clean and secure code
๐น Example: Without Encapsulation
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
s1 = Student("Arun", 85)
print(s1.marks) # Anyone can access and change
s1.marks = 40 # Can be changed easily
print(s1.marks)
๐ Example: With Encapsulation (using private variable)
class Student:
def __init__(self, name, marks):
self.name = name
self.__marks = marks # private variable
def get_marks(self): # getter
return self.__marks
def set_marks(self, value): # setter
if value >= 0 and value <= 100:
self.__marks = value
else:
print("Invalid marks!")
s1 = Student("Arun", 85)
print(s1.get_marks()) # Output: 85
s1.set_marks(95) # Valid update
print(s1.get_marks()) # Output: 95
s1.set_marks(150) # Invalid update
๐ What is __
(double underscore)?
- It makes the variable private.
- Cannot access it directly like
s1.__marks
- Must use getter and setter methods.
๐ง Real-Life Example:
ATM Machine:
- You can see balance, add money, withdraw money โ but you can’t open the system.
- That is encapsulation.
๐ Practice Questions with Answers
โ Q1: Create a class BankAccount
with private balance. Add deposit()
and get_balance()
methods.
โ Answer:
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("Balance:", acc.get_balance()) # Output: 1500
โ Q2: Make a class Person
with private age
. Use set_age()
to update age with condition (must be > 0).
โ Answer:
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
def get_age(self):
return self.__age
def set_age(self, new_age):
if new_age > 0:
self.__age = new_age
else:
print("Invalid age!")
p1 = Person("Ravi", 25)
print(p1.get_age())
p1.set_age(-10) # Invalid
p1.set_age(30) # Valid
print(p1.get_age()) # 30
๐ Summary
Word | Meaning |
---|---|
Encapsulation | Hide data inside class using private vars |
__ | Makes variable private |
Getter | Function to get value |
Setter | Function to set value safely |
๐ฃ Coming Up Next:
โก๏ธ Inheritance in Python | Learn How One Class Can Use Another
Leave a Reply