Encapsulated Bank Account

Medium ⏱ 12 min 61% acceptance ★★★★☆ 4.2
Build Account holding a balance in a single-underscore attribute _balance (the Python privacy convention). Provide deposit(amount) and withdraw(amount) that reject non-positive amounts and overdrafts by raising ValueError, and a read-only balance property. No direct writes from outside.

Examples

Example 1
Input
a = Account(100); a.deposit(50); a.balance
Output
150
Explanation

State changes only through methods.

Example 2
Input
a.withdraw(999)
Output
ValueError
Explanation

Overdraft rejected.

Constraints

  • balance is a @property with no setter.
  • Both mutators validate.

Topics

OOPencapsulation

Companies

HDFC BankGoldman SachsJPMorgan Chase

Hints

Hint 1

@property over a getter method.

Hint 2

Validation raises before mutating.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.