0
0
Pythonprogramming~30 mins

Purpose of encapsulation in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Purpose of Encapsulation in Python
📖 Scenario: Imagine you are creating a simple bank account system. You want to keep the account balance safe so that no one can change it directly by mistake. Instead, you want to control how the balance is changed using special methods.
🎯 Goal: Build a Python class that shows how encapsulation protects the account balance by making it private and allowing controlled access through methods.
📋 What You'll Learn
Create a class called BankAccount with a private variable __balance set to 1000
Add a method deposit that adds money to __balance
Add a method withdraw that subtracts money from __balance only if there is enough balance
Add a method get_balance that returns the current __balance
Show that direct access to __balance is not allowed
💡 Why This Matters
🌍 Real World
Encapsulation is used in real bank software to protect account balances and prevent unauthorized changes.
💼 Career
Understanding encapsulation is important for writing safe and reliable code in software development jobs.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance
Create a class called BankAccount with a private variable __balance set to 1000 inside the __init__ method.
Python
Need a hint?

Use self.__balance = 1000 inside the __init__ method to make the balance private.

2
Add deposit and withdraw methods
Add a method called deposit that takes amount and adds it to self.__balance. Add another method called withdraw that takes amount and subtracts it from self.__balance only if self.__balance is greater than or equal to amount.
Python
Need a hint?

Use self.__balance += amount in deposit and check balance before subtracting in withdraw.

3
Add a method to get the current balance
Add a method called get_balance that returns the value of self.__balance.
Python
Need a hint?

Return the private variable self.__balance in the get_balance method.

4
Show encapsulation by using the class and printing the balance
Create an object called account from BankAccount. Use deposit(500) and withdraw(200) methods on account. Then print the balance using print(account.get_balance()). Also, try to print account.__balance to show it is not accessible.
Python
Need a hint?

Use the methods to change balance and print it. Accessing __balance directly should cause an error.