Python Encapsulation: Hiding Data with Private Variables

🚀 Day 8/30 – Python OOPs Challenge 💡 Encapsulation in Python In real life, we don’t allow direct access to everything. For example: - You can use an ATM - But you cannot access the bank’s internal system That’s called Encapsulation. 🔹 What is Encapsulation? Encapsulation means: 👉 Wrapping data (variables) and methods together 👉 Restricting direct access to some data It helps in: - Data protection - Better control - Secure code 🔹 How to achieve Encapsulation in Python? We use private variables by adding double underscore __ 🔹 Example: ``` class BankAccount: def __init__(self, balance): self.__balance = balance # Private variable def deposit(self, amount): self.__balance += amount def show_balance(self): print("Balance:", self.__balance) acc = BankAccount(1000) acc.deposit(500) acc.show_balance() ``` 🔹 What happened here? - __balance cannot be accessed directly - We use methods to modify it This protects the data 🔒 📌 Key takeaway: Encapsulation = Data hiding + Controlled access 👉 Day 9: Public vs Private Variables (coming tomorrow) 👍 Like | 💬 Comment | 🔁 Share 📍 Follow me to learn Python OOP step by step #Python #OOP #LearningInPublic #30DaysOfPython #CodingJourney

🧠 Practice Question – Day 8 Create a class `Person` with: - private variable __age Create methods to: - set age - get age Try accessing age directly and see what happens 👀 Comment your code below 🚀

Like
Reply

To view or add a comment, sign in

Explore content categories