0
0
Pythonprogramming~30 mins

Property decorator usage in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Property Decorator in Python
📖 Scenario: You are creating a simple program to manage a bank account. You want to control how the account balance is accessed and updated safely.
🎯 Goal: Build a Python class called BankAccount that uses the @property decorator to get and set the account balance with validation.
📋 What You'll Learn
Create a class named BankAccount with a private attribute _balance.
Add a @property method called balance to get the current balance.
Add a setter for balance that only allows setting a non-negative value.
Print the balance after setting it.
💡 Why This Matters
🌍 Real World
Property decorators help control access to important data in programs, like bank balances, ensuring data stays valid.
💼 Career
Understanding property decorators is useful for writing clean, safe code in many Python jobs, especially in finance, data management, and software development.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance
Create a class called BankAccount with an __init__ method that sets a private attribute _balance to 0.
Python
Need a hint?

Use self._balance = 0 inside the __init__ method to create a private balance.

2
Add a property to get the balance
Add a @property method called balance inside the BankAccount class that returns self._balance.
Python
Need a hint?

Use @property above the balance method to make it a getter.

3
Add a setter to update the balance safely
Add a setter for balance using @balance.setter that sets self._balance only if the new value is not negative. If the value is negative, do not change self._balance.
Python
Need a hint?

Use @balance.setter to create the setter method. Check if value is not negative before setting.

4
Create an account, set balance, and print it
Create an instance of BankAccount called account. Set account.balance to 100. Then print account.balance.
Python
Need a hint?

Create the object, set the balance to 100, then print the balance to see the result.