Have you ever saved a secret in your diary with a lock? Or kept your chocolate hidden in a secret drawer? 🍫
That’s Encapsulation in real life!
In Python, Encapsulation is a way to hide or protect data so only certain parts of your code can use or change it. It helps kyour programs safe and organized — just like putting your stuff in a locker with a key!
🧠 What is Encapsulation?
Encapsulation means bundling data and the methods that work on that data into one unit — a class.
But more importantly:
-
It hides private data
-
It only allows controlled access
📦 Real-life Analogy
Think of a mobile phone:
-
You can use it (call, play games)
-
But you can’t open it and change the battery or circuit
That’s encapsulation — some parts are visible, and some are hidden to protect the system!
🐍 Let’s Learn with Python!
🎒 Class with Protected Data
📚 Try it Out:
💬 Output:
Why didn't s1.__marks = 30 work?
Because __marks is private — only accessible inside the class!
🕵️♂️ Accessing Private Data (Not Recommended)
You can access private data using a special trick, but it’s not safe and not advised:
This works, but we should avoid it. Instead, use getter/setter methods like update_marks().
✅ Why Use Encapsulation?
| Advantage | What it Means |
|---|---|
| 🎯 Controlled Access | Only allow safe changes to data |
| 🔒 Data Protection | Hide sensitive data from outside access |
| 📦 Clean Organization | Keep code tidy and manageable |
| 🚫 Prevent Misuse | Stop users from breaking your class logic |
🎮 Challenge for You!
Create a class BankAccount with:
-
Private balance
-
Method to show balance
-
Method to deposit and withdraw money
-
Prevent withdrawal if not enough money
Can you do it? Try it in your Python editor!
🧠 In Short
-
Encapsulation = Wrapping data and methods into a class
-
Use
__variableto make it private -
Control access with functions inside the class
📘 Exercise
1. Private Attribute Creation
Create a BankAccount class with:
-
A private attribute
__balance -
A method
deposit(amount)to increase balance -
A method
get_balance()to return the balance
Task: Create an object, deposit ₹1000, and print the balance.
2. Name Mangling Access
Using the BankAccount class from Q1, try accessing the __balance attribute directly from outside the class using name mangling.
Task: Demonstrate how to read and modify it without using getter/setter.
3. Private Method
Create a Car class with:
-
A private method
__engine_start()that prints"Engine started" -
A public method
start()that calls the private method
Task: Create an object and start the car.
4. Getter & Setter Methods
Create a Student class with a private attribute __marks.
-
Write getter and setter methods for
marks. -
The setter should validate that marks are between
0and100, otherwise reject.
Task: Test with valid and invalid marks.
5. Property Decorator
Rewrite Q4 using @property and @marks.setter instead of getter/setter methods.
Task: Show that student.marks = 85 works directly.
6. Encapsulation for Read-Only Attribute
Create a Book class with:
-
A private attribute
__isbn -
A read-only property
isbn
Task: Try changing ISBN from outside and show it fails.
7. Encapsulation in Inheritance
Create a Person class with a private attribute __age.
Create a Teacher class that inherits from Person.
Task: Show that Teacher objects cannot access __age directly.
8. Encapsulation with Method Overriding
Create a Device class with:
-
A private attribute
__status -
A public method
turn_on()that sets status to "ON" -
A public method
turn_off()that sets status to "OFF"
Create a subclassSmartDevicethat overridesturn_on()to print"Smart device starting..."before turning on.
Task: Demonstrate usage.
9. Encapsulation with List of Objects
Create a Library class with:
-
A private list
__books -
Methods
add_book(title)andget_books()
Task: Add books and print them without directly accessing__books.
10. Secure Attribute Access
Create a User class with:
-
Private attribute
__password -
Method
set_password(pwd)that stores password only if it meets certain criteria (min 8 chars, contains number & letter) -
Method
check_password(pwd)to verify if entered password matches stored one
Task: Test with valid and invalid passwords.