Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / Python Tutorial / Chapter 5: Object-Oriented Programming (OOP)
PYTHON ⏱ 12 min read

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

Encapsulation in Python: • Public: `self.name` (accessible anywhere). • Protected: `self._balance` (single underscore: convention indicating internal use). • Private: `self.__balance` (double underscore: triggers name mangling, preventing direct outside access). • Getters and Setters: Use the `@property` decorator to create pythonic getters and setters with validation rules.

Syntax Structure

Syntax Blueprint
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance # Private

    @property
    def balance(self):
        return self.__balance

Code Example

PYTHON Code
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

• `__balance` is private to `StudentAccount`. • `@property` exposes a clean read-only interface. • `@balance.setter` intercepts writes and rejects negative numbers.

Expected Output

Anand Joshi Balance: ₹2500 Updated Balance: ₹1000 Validation intercepted: Account balance cannot be negative!

Real-World Application

Used across financial systems, banking portals, and sensitive user account records.

Common Mistakes to Avoid

• Writing verbose Java-style `get_balance()` and `set_balance()` methods instead of Python's clean `@property` decorator. • Assuming private `__var` is 100% cryptographic security (Python uses name mangling `_ClassName__var`).

Quick Practice Challenge

Create a class with a private `__temperature` attribute and a `@property` that prevents temperatures below absolute zero (-273.15°C).

Key Takeaways

• Prefix private attributes with double underscore `__`. • Use `@property` for clean pythonic getters and setters. • Polymorphism lets disparate classes share identical interface method names.