Public vs. Private Attributes and Getter/Setter Methods
Lesson Overview
This lesson covers how to control access to object data using getter and setter methods. It also introduces Public Attributes (accessible from anywhere) and Private Attributes (hidden inside the class). Getters and setters allow you to safely retrieve or modify these private attributes, often adding checks to ensure data is valid before changing it
Lesson Content
The Need for Security: Protecting the Bank Vault
You already know how to update data directly (like car.speed = 100). While this is fine for simple things like a car's color, imagine if we were dealing with a Bank Account.
If we used the "Open Hood" approach here, anyone could accidentally set a negative balance or—even worse—a random person could directly change an account holder's name or PIN without any verification. That is not okay. We need "Security Guards" to control who sees the data and how it gets changed.
The Solution: Private Variables
To solve this, Python allows us to make variables Private. This effectively locks the data inside a safe. You can't just reach in and grab it anymore; the direct access is blocked.
In Python, we distinguish between public and private data using underscores.
- Public:
self.attribute(Accessible anywhere) - Private:
self.__attribute(Hidden, typically only accessible inside the class)
class BankAccount:
def __init__(self, name, balance):
self.name = name # Public: Anyone can see the name
self.__balance = balance # Private: Hidden inside the vault!
account = BankAccount("Ajay", 1000)
# We can access the public variable easily
print(account.name) # Output: Ajay
# But trying to access the private variable directly causes an error!
# print(account.__balance)
# AttributeError: 'BankAccount' object has no attribute '__balance'Why Double Underscores (__)?
When you use double underscores, Python uses NAME MANGLING. It internally renames __balance to _BankAccount__balance (_CLASS_NAME__attribute). This makes it hard (though technically possible) for someone to bypass it.
Single underscore (_balance):
- Convention: "This is protected, don't access directly"
- Python doesn't enforce it (just a suggestion)
Double underscore (__balance):
- Python actively hides it through name mangling
- Stronger protection
Try this in Python:
💬 Comments (0)
Login to join the discussion
No comments yet. Be the first to share your thoughts!