Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use a Protected Attribute in a Subclass

Practice accessing and updating a protected attribute from a subclass to implement behavior.

Python practice9 minEncapsulation & Access PatternsBeginnerLast updated April 8, 2026

Problem statement

You have a base class BankAccount that stores an account balance in a protected attribute _balance and provides deposit functionality. Implement a subclass SavingsAccount that exposes a withdraw(amount) method which: - Attempts to subtract amount from the protected _balance. - If amount is greater than the available balance, do not change the balance and return False. - If the withdrawal is successful, subtract the amount and return True. Also ensure the public balance property returns the current balance rounded to 2 decimal places. Provide small helper functions so tests can create accounts, perform operations, and inspect balances.

Task

Implement a SavingsAccount subclass that uses a protected _balance attribute from the base BankAccount to perform withdrawals safely.

Examples

Successful withdrawal

Input

withdraw_and_get_balance(100, 30)

Output

70.0

Withdrawing 30 from 100 leaves 70.

Input format

Use provided helper functions such as withdraw_and_get_balance(initial_balance, amount).

Output format

Functions return numeric balances or booleans; tests compare their string representations.

Constraints

- Use the protected attribute convention (_balance) in the base class and have the subclass directly access it. - balance property returns rounded value to 2 decimal places. - withdraw returns a boolean indicating success.

Samples

Sample 1

Input

withdraw_and_get_balance(50, 60)

Output

50.0

Attempting to withdraw more than the balance fails and leaves balance unchanged.