π Day 18: Encapsulation in Python – Keep It Safe, Keep It Clean
Imagine you’re using an ATM. You insert your card, enter your PIN, and withdraw money.
But do you ever get to see how the system processes the transaction internally?
Nope. That’s encapsulation in action.
In Python, encapsulation means hiding internal details and only exposing what is necessary.
It’s a core concept of object-oriented programming and helps make your code more secure and easy to manage.
π The Core Idea
Encapsulation allows you to bundle data (variables) and behavior (methods) together inside a class, and restrict access to some parts of it.
π§ In Simple Words:
-
You can hide the internal state of an object from the outside world.
-
You only allow controlled access via methods.
Here, the balance can be directly modified, even to an invalid amount like negative money.
This is not safe. So how do we protect it?
π‘ With Encapsulation (Private Variables)
In Python, you can prefix variables with double underscores (__) to make them private.
Now the balance is protected.
You can only access or modify it using specific methods like deposit, withdraw, etc.
π But Wait... Can’t I Still Access It?
Yes, Python allows access using name mangling:
print(account._BankAccount__balance) # π¬ Technically possible, but strongly discouraged!
So encapsulation in Python is more about convention and intention —
We trust developers to respect boundaries.
π Getters and Setters
You can also create methods to get or set private values. These are called:
-
Getter – method to read value
-
Setter – method to update value
π¦ Real-Life Analogy
Just like your ATM card doesn’t show you bank's internal code,
Encapsulation ensures only necessary parts of the object are accessible, keeping the rest safe from accidental or unauthorized changes.
✅ Key Takeaways
-
Encapsulation hides internal details of objects.
-
Use
__variableto make it private. -
Create getters and setters for safe access.
-
It improves security, code organization, and maintenance.
π Challenge for You
Create a class Employee with private variables: name, salary.
Write getter and setter methods.
Allow only salary updates above ₹10,000.
Let’s see you implement some real-world encapsulation!
Keep This In Mind:
“Good code is like a secure diary — it hides what’s private and reveals only what’s needed.”




Comments
Post a Comment