0
0
Pythonprogramming~15 mins

Private attributes in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Private Attributes in Python
📖 Scenario: Imagine you are creating a simple bank account system. You want to keep the account balance safe so that it cannot be changed directly from outside the account. This is where private attributes help.
🎯 Goal: You will create a class with a private attribute for the account balance. Then, you will add a method to safely check the balance.
📋 What You'll Learn
Create a class called BankAccount
Add a private attribute called __balance with the value 1000
Add a method called get_balance that returns the value of __balance
Create an object called account from the BankAccount class
Print the balance using the get_balance method
💡 Why This Matters
🌍 Real World
Private attributes help protect important data inside objects, like bank balances, so they cannot be changed accidentally or by mistake.
💼 Career
Understanding private attributes is important for writing safe and reliable code in many programming jobs, especially when working with classes and objects.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance
Create a class called BankAccount with a private attribute __balance set to 1000 inside the __init__ method.
Python
Need a hint?

Use self.__balance = 1000 inside the __init__ method to create a private attribute.

2
Add a method to get the balance
Inside the BankAccount class, add a method called get_balance that returns the private attribute __balance.
Python
Need a hint?

Define get_balance to return self.__balance.

3
Create an account object
Create an object called account from the BankAccount class.
Python
Need a hint?

Create the object by writing account = BankAccount().

4
Print the account balance
Use the print function to display the balance by calling account.get_balance().
Python
Need a hint?

Print the balance by calling account.get_balance().