Encapsulation in Python

Encapsulation is a fundamental concept in object-oriented programming (OOP) that restricts direct access to some of an object's attributes and methods. It is a protective barrier that prevents the data from being accessed directly and modified accidentally. In Python, encapsulation is achieved through the use of private and public access modifiers.

Characteristics of Encapsulation

Example of Encapsulation

This example demonstrates how to use encapsulation in Python by defining a class with private attributes and public methods to access and modify those attributes.

Code Example

class BankAccount:
            def __init__(self, account_number, balance):
                self.__account_number = account_number  # Private attribute
                self.__balance = balance  # Private attribute
        
            # Getter method for balance
            def get_balance(self):
                return self.__balance
        
            # Method to deposit money
            def deposit(self, amount):
                if amount > 0:
                    self.__balance += amount
                    print(f"Deposited: {amount}")
                else:
                    print("Invalid deposit amount")
        
            # Method to withdraw money
            def withdraw(self, amount):
                if 0 < amount <= self.__balance:
                    self.__balance -= amount
                    print(f"Withdrew: {amount}")
                else:
                    print("Invalid withdrawal amount or insufficient funds")
        
        # Creating an instance of BankAccount
        account = BankAccount("123456789", 1000)
        
        # Demonstrating encapsulation
        account.deposit(500)  # Output: Deposited: 500
        print("Balance:", account.get_balance())  # Output: Balance: 1500
        account.withdraw(200)  # Output: Withdrew: 200
        print("Balance:", account.get_balance())  # Output: Balance: 1300
        

Output

Deposited: 500
Balance: 1500
Withdrew: 200
Balance: 1300

Conclusion

Encapsulation is an essential principle in Python that promotes data hiding and controlled access to an object's attributes and methods. By using private attributes and providing public methods for interaction, encapsulation helps maintain the integrity of the data and makes the code more maintainable and easier to understand.