Python Program to Implement Encapsulation

Introduction

Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, or class. Encapsulation restricts direct access to some of an object’s components, which is a means of preventing unintended interference and misuse of the data. The concept of encapsulation is often achieved by making some attributes private (not accessible from outside the class) and providing public methods to access and modify them.

In Python, encapsulation is implemented by defining class attributes as private using a double underscore prefix (__). The private attributes can only be accessed within the class itself, while public methods can be used to interact with these attributes.

This tutorial will guide you through creating a Python program that demonstrates encapsulation by defining a class with private attributes and public methods to access and modify them.

Example:

  • Class: Account
  • Attributes: __account_number (private), __balance (private)
  • Methods: deposit() (public), withdraw() (public), get_balance() (public)
  • Program Output:
    Initial Balance: 1000
    After Deposit: 1500
    After Withdrawal: 1200
    

Problem Statement

Create a Python program that:

  • Defines a class named Account with private attributes __account_number and __balance.
  • Provides public methods deposit(), withdraw(), and get_balance() to interact with the private attributes.
  • Creates an object of the Account class and uses the public methods to demonstrate encapsulation.

Solution Steps

  1. Define the Account Class: Use the class keyword to define a class named Account.
  2. Add Private Attributes: Define private attributes __account_number and __balance within the class.
  3. Add a Constructor Method: Define the __init__ method to initialize the private attributes.
  4. Add Public Methods: Define public methods deposit, withdraw, and get_balance to interact with the private attributes.
  5. Create an Object: Instantiate an object of the Account class with an initial balance.
  6. Use Public Methods: Call the public methods on the Account object to deposit, withdraw, and check the balance.

Python Program

# Python Program to Implement Encapsulation
# Author: https://www.rameshfadatare.com/

# Step 1: Define the Account Class
class Account:
    # Step 2: Add Private Attributes
    def __init__(self, account_number, initial_balance):
        self.__account_number = account_number
        self.__balance = initial_balance
    
    # Step 4: Add Public Method to Deposit Money
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
        else:
            print("Deposit amount must be positive")
    
    # Step 4: Add Public Method to Withdraw Money
    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient balance or invalid withdrawal amount")
    
    # Step 4: Add Public Method to Get Current Balance
    def get_balance(self):
        return self.__balance

# Step 5: Create an Object of the Account Class
my_account = Account("12345678", 1000)

# Step 6: Use Public Methods to Interact with the Account
print(f"Initial Balance: {my_account.get_balance()}")

# Deposit money
my_account.deposit(500)
print(f"After Deposit: {my_account.get_balance()}")

# Withdraw money
my_account.withdraw(300)
print(f"After Withdrawal: {my_account.get_balance()}")

Explanation

Step 1: Define the Account Class

  • The Account class is defined using the class keyword. This class represents a bank account with specific attributes and methods.

Step 2: Add Private Attributes

  • The __account_number and __balance attributes are defined with a double underscore prefix (__), making them private. These attributes can only be accessed within the class itself.

Step 3: Add a Constructor Method

  • The __init__ method initializes the __account_number and __balance attributes when a new Account object is created. The constructor accepts the account number and initial balance as parameters.

Step 4: Add Public Methods

  • deposit(amount): This method allows money to be deposited into the account. It adds the specified amount to the __balance, provided the amount is positive.
  • withdraw(amount): This method allows money to be withdrawn from the account. It subtracts the specified amount from the __balance, provided the amount is positive and does not exceed the available balance.
  • get_balance(): This method returns the current balance of the account. It allows external code to view the balance without directly accessing the private attribute __balance.

Step 5: Create an Object

  • An Account object named my_account is created with an initial balance of 1000.

Step 6: Use Public Methods

  • The deposit, withdraw, and get_balance methods are called on the my_account object to demonstrate how encapsulation protects the account’s data while allowing controlled access through public methods.

Output Example

Example Output:

Initial Balance: 1000
After Deposit: 1500
After Withdrawal: 1200

Additional Examples

Example 1: Accessing Private Attributes (Not Recommended)

# Attempting to access private attributes directly (this will raise an error)
try:
    print(my_account.__balance)
except AttributeError as e:
    print(e)

Output:

'Account' object has no attribute '__balance'
  • This example demonstrates that trying to access a private attribute directly from outside the class results in an AttributeError.

Example 2: Modifying Private Attributes via Public Methods

# Using public methods to modify the private attributes
my_account.deposit(1000)
my_account.withdraw(500)
print(f"Final Balance: {my_account.get_balance()}")

Output:

Final Balance: 1700
  • This example shows how public methods can be used to safely modify and access private attributes.

Example 3: Protecting Data Integrity with Encapsulation

# Demonstrating data integrity protection
my_account.deposit(-100)  # Invalid deposit
my_account.withdraw(5000)  # Invalid withdrawal
print(f"Protected Balance: {my_account.get_balance()}")

Output:

Deposit amount must be positive
Insufficient balance or invalid withdrawal amount
Protected Balance: 1700
  • This example highlights how encapsulation helps protect data integrity by enforcing rules on how the data can be modified.

Conclusion

This Python program demonstrates how to implement encapsulation, a key concept in object-oriented programming that restricts direct access to an object’s attributes and methods. Encapsulation helps protect the internal state of an object and allows controlled access through public methods. Understanding encapsulation is essential for writing secure, maintainable, and robust Python programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top