257 lines
9.0 KiB
Python
257 lines
9.0 KiB
Python
# 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 |