Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Expose an Attribute with a Read-Only Property

Create a BankAccount class exposing balance via a read-only property while allowing controlled updates via methods.

Python practice10 minMethods & PropertiesBeginnerLast updated April 7, 2026

Problem statement

Implement a BankAccount class that stores a private _balance and exposes it via a read-only property balance (no setter). Provide two methods: - deposit(amount): adds amount to the balance. If amount is negative, raise ValueError. - withdraw(amount): subtracts amount from the balance and returns True if successful; if amount is greater than the current balance or amount is negative, do not modify balance and return False. The balance attribute should be accessible via account.balance, but attempts to set account.balance should not be possible (there should be no setter). Tests will verify that balance is readable and that it cannot be assigned by checking that the property's fset is None.

Task

Learn how to use @property to expose a read-only attribute and mutate internal state via instance methods.

Examples

Deposit increases balance

Input

(lambda a: (a.deposit(50), a.balance)[1])(BankAccount(100))

Output

150

Start with 100, deposit 50, balance becomes 150. The expression uses a lambda to perform multiple operations in one expression.

Input format

All tests call the BankAccount class and its methods in single-expression form (no prints).

Output format

Expressions should evaluate to numeric balances or booleans depending on the test.

Constraints

Do not define a setter for balance. Use an internal attribute named _balance. deposit raises ValueError for negative amounts. withdraw returns a boolean and must not allow overdrafts.

Samples

Sample 1

Input

(lambda a: (a.withdraw(30), a.balance)[1])(BankAccount(100))

Output

70

Withdrawing 30 from 100 leaves 70 and withdraw returns True (unused here).