Python Encapsulation
1. What is Encapsulation?
Encapsulation means keeping data safe inside a class.
In simple words:
👉 Data and methods are wrapped together
👉 Outside code cannot directly change important data
👉 We control how data is accessed
2. Real-Life Example
Think of an ATM machine 🏧
-
You cannot see money inside
-
You use buttons to withdraw
Same idea in Python:
-
Data is hidden
-
Methods control access
3. Public, Protected, and Private Variables
Public Variable
Can be accessed anywhere.
Protected Variable (_)
Means “use carefully”.
Private Variable (__)
Cannot be accessed directly.
4. Access Private Variable Using Method
Example
5. Change Private Variable Safely
Example
6. Why Encapsulation is Important?
✔ Keeps data safe
✔ Prevents wrong changes
✔ Makes code secure
✔ Easy to manage
7. Encapsulation with Getter and Setter
Example
8. Encapsulation Using property()
Example
9. Common Beginner Mistakes
❌ Accessing Private Variable Directly
❌ Error.
❌ Not Using Methods for Sensitive Data
👉 Data can be misused.
10. Simple Practice Examples
Example 1: Bank Account
Example 2: Password
Example 3: Temperature
11. Summary (Python Encapsulation)
✔ Encapsulation hides data
✔ Uses private variables
✔ Access through methods
✔ Makes program secure
✔ Important OOP concept
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Abstraction
-
Data Hiding
-
OOP Mini Projects
Just tell me 😊
