Polymorphism, Encapsulation and Private Attributes
Encapsulation safeguards internal data from outside tampering, while polymorphism allows different objects to respond to the same method call.
What is it?
• Encapsulation: Bundling data and methods into a single unit while hiding internal implementation details. • Polymorphism: The ability for different classes to implement methods with the same name, behaving appropriately for each class.
Why is it used?
Prevents unauthorized state modification, simplifies API interfaces, and ensures secure data models.
Detailed Explanation
Syntax Structure
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private
@property
def balance(self):
return self.__balance
Code Example
class StudentAccount:
def __init__(self, student_name, initial_balance=2500):
self.student_name = student_name
self.__balance = initial_balance # Private attribute (name mangled)
# Getter Property
@property
def balance(self):
return self.__balance
# Setter Property with Validation
@balance.setter
def balance(self, new_balance):
if new_balance < 0:
raise ValueError("Account balance cannot be negative!")
self.__balance = new_balance
account = StudentAccount("Anand Joshi", 2500)
print(f"{account.student_name} Balance: ₹{account.balance}")
# Updating via validated setter
account.balance = 1000
print(f"Updated Balance: ₹{account.balance}")
# Direct private access fails
try:
account.__balance = -500 # Does NOT modify the real private variable!
account.balance = -500 # Triggers setter validation
except ValueError as e:
print(f"Validation intercepted: {e}")
Explanation of the Code
Expected Output
Real-World Application
Used across financial systems, banking portals, and sensitive user account records.
Common Mistakes to Avoid
Quick Practice Challenge
Create a class with a private `__temperature` attribute and a `@property` that prevents temperatures below absolute zero (-273.15°C).