Skip to content

Commit cee29eb

Browse files
committed
feat(other): add basic BankAccount OOP class
1 parent 15f5588 commit cee29eb

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

other/bank_account.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Simple BankAccount class demonstrating core OOP concepts.
3+
"""
4+
5+
6+
class BankAccount:
7+
"""
8+
Basic bank account model with encapsulated account number and balance.
9+
10+
>>> account = BankAccount("ACC-1001", initial_balance=100.0)
11+
>>> account.balance
12+
100.0
13+
>>> account.deposit(50)
14+
150.0
15+
>>> account.withdraw(20)
16+
130.0
17+
>>> account.account_number
18+
'ACC-1001'
19+
"""
20+
21+
def __init__(self, account_number: str, initial_balance: float = 0.0) -> None:
22+
if not account_number:
23+
raise ValueError("account_number must be provided")
24+
if initial_balance < 0:
25+
raise ValueError("initial_balance cannot be negative")
26+
27+
self.__account_number = account_number
28+
self._balance = float(initial_balance)
29+
30+
@property
31+
def account_number(self) -> str:
32+
"""Read-only public accessor for the encapsulated account number."""
33+
return self.__account_number
34+
35+
@property
36+
def balance(self) -> float:
37+
"""Current account balance."""
38+
return self._balance
39+
40+
def deposit(self, amount: float) -> float:
41+
"""Deposit a positive amount and return updated balance."""
42+
if amount <= 0:
43+
raise ValueError("deposit amount must be positive")
44+
self._balance += amount
45+
return self._balance
46+
47+
def withdraw(self, amount: float) -> float:
48+
"""Withdraw a positive amount and return updated balance."""
49+
if amount <= 0:
50+
raise ValueError("withdraw amount must be positive")
51+
if amount > self._balance:
52+
raise ValueError("insufficient funds")
53+
self._balance -= amount
54+
return self._balance
55+
56+
57+
if __name__ == "__main__":
58+
import doctest
59+
60+
doctest.testmod()

0 commit comments

Comments
 (0)