init commit; source - Intermediate Python - recorded for Frontend Masters; Created by Nina Zakharenko; https://www.learnpython.dev

This commit is contained in:
aman committed 2026-03-29 13:34:42 +02:00
commit d7a3dff32e
4 files changed
+2486

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
# Create a BankAccount class
# An __init__ that takes owner (string) and optional balance (defaults to 0)
# A deposit method that adds money and returns the new balance
# A withdraw method that subtracts money — but should prevent overdraft (no negative balance)
# A __repr__ that shows something like BankAccount('Alice', balance=500)
from typing import Optional # trying it out with optional
from datetime import datetime
# Add @property to your BankAccount class to protect the balance:
# Make balance a private attribute (_balance)
# Create a @property so you can still read it with acc.balance
# Create a @balance.setter that prevents setting a negative value
# Add a @property for owner that's read-only (no setter — nobody should rename the account owner)
class BankAccount:
@property
def balance(self):
return self._balance
## now setter ### should i now comment out these in the init dunder?
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
else:
self._balance = value
@property
def owner(self):
return self._owner
def __init__(self, owner: str, balance: Optional[float] = None) -> None: # how do i provide a type hint here? is there a better way to mark something as optional?? how do i specify type here?
self._owner = owner
self.balance = balance if balance is not None else 0
self._history = []
def __repr__(self): # how would i improve this with best practices??
# return f"Account: {self._owner}, balance: {self.balance}" # a much better way would be - return(f"BankAccount({self._owner, self.balance})")
return f"BankAccount('{self.owner}', balance = {self.balance})"
def __str__(self):
return f"yes, {self.owner} has an account of good standing with {self.balance} balance in the bank. "
def deposit(self, money):
self.balance += money
self._history.append(Transaction("deposit", money))
return self.balance
def withdraw(self, money):
if (self.balance - money) >= 0:
self.balance -= money
self._history.append(Transaction("withdraw", money))
else:
# print("Overdraft not possible")
raise InsufficientFundsError(self.balance, money)
return self.balance
def get_history(self):
return self._history
## this is the testing framework -
# acc = BankAccount("Alice", 100)
# print(acc) # BankAccount('Alice', balance=100)
# acc.deposit(50) # returns 150
# print(acc)
# acc.withdraw(30) # returns 120
# print(acc)
# acc.withdraw(200) # should print a warning and not withdraw
# print(repr(acc))
###
# Inheritance — the core of OOP (SavingsAccount extends BankAccount)
# Exceptions — custom error classes are themselves a great inheritance exercise
# @property — encapsulation, controlling access to data
# Track transaction history — composition (objects containing objects/lists)
# Dunder methods (__add__, __len__, __eq__) — operator overloading
# Transfer method — objects interacting with each other
# ---
# Create a SavingsAccount class that inherits from BankAccount:
# It takes owner, optional balance, and an interest_rate (like 0.05 for 5%)
# It should use super() to reuse the parent's __init__
# Add an apply_interest() method that increases the balance by the interest rate
# Override withdraw so it blocks withdrawals above 1000 (savings protection), but otherwise works normally
# Update __repr__ to also show the interest rate
class SavingsAccount(BankAccount):
def __init__(self, owner, balance = None, interest_rate: float = 0.05): # should balance be just None or should i do the same optional thing as I did for BankAccount class?
super().__init__(owner, balance)
self.interest_rate = interest_rate
def __repr__(self):
return f"SavingsAccount('{self.owner}', balance = {self.balance}, interest rate = {self.interest_rate})"
def apply_interest(self):
self.balance += self.balance * self.interest_rate
return self.balance# would this work?
def withdraw(self, money): # how to properly do the override? is this the right way?
if money >= 1000:
print("Transactions above 1000 are not allowed")
else:
return super().withdraw(money)
# ---
# savings = SavingsAccount("Alice", 1000, 0.05)
# print(repr(savings)) # shows owner, balance, and interest rate
# savings.apply_interest()
# print(savings) # balance becomes 1050.0
# savings.withdraw(500) # works fine
# print(savings)
# savings.withdraw(1500) # blocked — too large for savings
# print(savings)
# savings.deposit(200) # should still work (inherited)
# print(savings)
# Create a Classroom class that:
# __init__ takes a teacher (string) and starts with an empty list of students
# An add_student method that takes a name and a grade (store them as a dict like {"name": "Alice", "grade": 85})
# __getitem__ — lets you do classroom[0] to get a student
# __len__ — returns number of students
# __eq__ — two classrooms are equal if they have the same number of students
# __lt__ — for comparing/sorting classrooms by number of students
# __repr__
class Classroom:
def __init__(self, teacher: str) -> None:
self.teacher = teacher
self.students = []
def add_student(self, name: str, grade: float):
self.students.append({"name":name, "grade":grade})
def __str__(self):
return f"The teacher is {self.teacher} and the students are {self.students}"
def __repr__(self):
return f"Classroom({self.teacher})"
def __getitem__(self, key):
return self.students[key]
def __len__(self):
return len(self.students)
def __eq__(self, value):
return len(self.students) == len(value.students)
def __lt__(self, other):
return len(self.students) < len(other.students)
# c1 = Classroom("Mr. Smith")
# c1.add_student("Alice", 85)
# c1.add_student("Bob", 92)
# c1.add_student("Charlie", 78)
# print(c1[0]) # {'name': 'Alice', 'grade': 85}
# print(c1[-1]) # {'name': 'Charlie', 'grade': 78}
# c2 = Classroom("Ms. Jones")
# c2.add_student("Diana", 90)
# print(c1 == c2) # False
# print(c1 > c2) # True
# print(sorted([c1, c2])) # c2 first (fewer students)
# Create a custom InsufficientFundsError and integrate it into your BankAccount class:
# Create an InsufficientFundsError class that inherits from Exception
# Its __init__ should take balance and amount (the attempted withdrawal)
# It should have a meaningful error message like "Cannot withdraw 500. Balance is only 200."
# Update BankAccount.withdraw to raise this error instead of printing
# Use try/except when calling withdraw to handle it gracefully
class InsufficientFundsError(Exception):
def __init__(self, balance, amount): # explain to me what this is - *args
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {self.amount}. Balance is only {self.balance}")
# acc = BankAccount("Alice", 200)
# try:
# acc.withdraw(500)
# except InsufficientFundsError as e:
# print(e) # Cannot withdraw 500. Balance is only 200.
# print(e.balance) # 200
# print(e.amount) # 500
# acc.withdraw(50) # works fine, no error
# acc = BankAccount("Alice", 100)
# print(acc.balance) # 100 — reading works
# acc.balance = 500 # setting works
# print(acc.balance) # 500
# #acc.balance = -50 # should raise ValueError
# print(acc.owner) # Alice — reading works
# acc.owner = "Bob" # should raise AttributeError (read-only)
# ---
# Write tests for your SavingsAccount class:
# Test that apply_interest calculates correctly
# Test that withdrawals over 1000 are blocked
# Test that deposit still works (inherited)
# Test that the interest rate is stored correctly
## done, check the tests_bankclass.py
# ---
# Add transaction history to your BankAccount:
# Create a Transaction class with type, amount, and timestamp
# Add _history = [] in BankAccount.__init__
# In deposit, create a Transaction("deposit", money) and append it to _history
# Do the same in withdraw with "withdrawal"
# Add get_history() that returns the list
# Add __repr__ to Transaction
class Transaction:
def __init__(self, type: str, amount: float) -> None:
self.type = type
self.amount = amount
self.timestamp = datetime.now
def __repr__(self):
return f"Transaction(type='{self.type}', amount={self.amount}, time={self.timestamp})"
# test the above
acc = BankAccount("Alice", 100)
acc.deposit(50)
acc.deposit(200)
acc.withdraw(30)
for t in acc.get_history():
print(t)
# Transaction(type='deposit', amount=50, time=...)
# Transaction(type='deposit', amount=200, time=...)
# Transaction(type='withdrawal', amount=30, time=...)
print(len(acc.get_history())) # 3
+228
View File
@@ -0,0 +1,228 @@
"""
Python OOP Practice
===================
Concepts covered:
1. Classes & __init__
2. @property & encapsulation
3. Custom exceptions (inheritance from Exception)
4. Composition (Transaction history)
5. Inheritance (SavingsAccount)
6. Dunder methods (__repr__, __str__, __getitem__, __len__, __eq__, __lt__)
"""
from typing import Optional
from datetime import datetime
# =============================================================================
# 1. CUSTOM EXCEPTIONS
# =============================================================================
class InsufficientFundsError(Exception):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {self.amount}. Balance is only {self.balance}")
# =============================================================================
# 2. COMPOSITION — Transaction class (used by BankAccount)
# =============================================================================
class Transaction:
"""Represents a single bank transaction."""
def __init__(self, type: str, amount: float) -> None:
self.type = type
self.amount = amount
self.timestamp = datetime.now()
def __repr__(self):
return f"Transaction(type='{self.type}', amount={self.amount}, time={self.timestamp})"
# =============================================================================
# 3. BASE CLASS — BankAccount
# Demonstrates: @property, encapsulation, composition, custom exceptions
# =============================================================================
class BankAccount:
"""A bank account with balance protection and transaction history."""
def __init__(self, owner: str, balance: Optional[float] = None) -> None:
self._owner = owner
self.balance = balance if balance is not None else 0 # triggers setter
self._history = []
# --- Properties ---
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = value
@property
def owner(self):
"""Read-only property — owner cannot be changed."""
return self._owner
# --- Core methods ---
def deposit(self, money):
self.balance += money
self._history.append(Transaction("deposit", money))
return self.balance
def withdraw(self, money):
if (self.balance - money) >= 0:
self.balance -= money
self._history.append(Transaction("withdrawal", money))
else:
raise InsufficientFundsError(self.balance, money)
return self.balance
def get_history(self):
return self._history
# --- Dunder methods ---
def __repr__(self):
return f"BankAccount('{self.owner}', balance={self.balance})"
def __str__(self):
return f"{self.owner}'s account — balance: {self.balance}"
# =============================================================================
# 4. INHERITANCE — SavingsAccount extends BankAccount
# =============================================================================
class SavingsAccount(BankAccount):
"""A savings account with interest and withdrawal limits."""
def __init__(self, owner, balance=None, interest_rate: float = 0.05):
super().__init__(owner, balance)
self.interest_rate = interest_rate
def apply_interest(self):
self.balance += self.balance * self.interest_rate
return self.balance
def withdraw(self, money):
if money >= 1000:
print("Transactions above 1000 are not allowed")
return self.balance
return super().withdraw(money)
def __repr__(self):
return f"SavingsAccount('{self.owner}', balance={self.balance}, rate={self.interest_rate})"
# =============================================================================
# 5. DUNDER METHODS — Classroom (container behavior + comparison)
# =============================================================================
class Classroom:
"""Demonstrates __getitem__, __len__, __eq__, __lt__ for container behavior."""
def __init__(self, teacher: str) -> None:
self.teacher = teacher
self.students = []
def add_student(self, name: str, grade: float):
self.students.append({"name": name, "grade": grade})
def __getitem__(self, key):
return self.students[key]
def __len__(self):
return len(self.students)
def __eq__(self, other):
return len(self.students) == len(other.students)
def __lt__(self, other):
return len(self.students) < len(other.students)
def __repr__(self):
return f"Classroom('{self.teacher}', students={len(self.students)})"
def __str__(self):
return f"Teacher: {self.teacher}, Students: {self.students}"
# =============================================================================
# 6. TESTS — Uncomment sections to test each feature
# =============================================================================
if __name__ == "__main__":
# --- BankAccount basics ---
print("=== BankAccount ===")
acc = BankAccount("Alice", 100)
print(acc)
acc.deposit(50)
print(f"After deposit: {acc.balance}")
acc.withdraw(30)
print(f"After withdraw: {acc.balance}")
# --- Custom exception ---
print("\n=== InsufficientFundsError ===")
try:
acc.withdraw(500)
except InsufficientFundsError as e:
print(e)
print(f" Balance: {e.balance}, Attempted: {e.amount}")
# --- Property protection ---
print("\n=== Property Protection ===")
print(f"Owner: {acc.owner}")
try:
acc.owner = "Bob"
except AttributeError:
print("Cannot change owner — read-only")
try:
acc.balance = -50
except ValueError as e:
print(f"Cannot set negative balance: {e}")
# --- Transaction history ---
print("\n=== Transaction History ===")
for t in acc.get_history():
print(f" {t}")
print(f"Total transactions: {len(acc.get_history())}")
# --- SavingsAccount ---
print("\n=== SavingsAccount ===")
savings = SavingsAccount("Alice", 1000, 0.05)
print(repr(savings))
savings.apply_interest()
print(f"After interest: {savings.balance}")
savings.withdraw(500)
print(f"After withdraw: {savings.balance}")
savings.withdraw(1500)
savings.deposit(200)
print(f"After deposit: {savings.balance}")
# --- Classroom ---
print("\n=== Classroom ===")
c1 = Classroom("Mr. Smith")
c1.add_student("Alice", 85)
c1.add_student("Bob", 92)
c1.add_student("Charlie", 78)
c2 = Classroom("Ms. Jones")
c2.add_student("Diana", 90)
print(f"c1[0]: {c1[0]}")
print(f"len(c1): {len(c1)}")
print(f"c1 == c2: {c1 == c2}")
print(f"c1 > c2: {c1 > c2}")
print(f"Sorted: {sorted([c1, c2])}")
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
from bankclass import SavingsAccount
import unittest
class TestBankClass(unittest.TestCase):
def setUp(self):
self.acc = SavingsAccount("Alice", 1000, 0.05)
def test_apply_interest(self):
self.assertEqual(self.acc.apply_interest(), 1050)
def test_savings_withdraw(self):
self.acc.withdraw(400)
self.assertEqual(self.acc.balance, 600)
if __name__ == "__main__":
unittest.main()
# ---
# now do with higher level pytests instead