|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import TypeVar |
| 3 | +import random |
| 4 | + |
| 5 | +# Create TBankAccount type bound by the BankAccount class |
| 6 | +TBankAccount = TypeVar("TBankAccount", bound="BankAccount") |
| 7 | + |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class BankAccount: |
| 11 | + account_number: int |
| 12 | + balance: float |
| 13 | + |
| 14 | + def display_balance(self: TBankAccount) -> TBankAccount: |
| 15 | + print(f"Account Number: {self.account_number}") |
| 16 | + print(f"Balance: ${self.balance:,.2f}\n") |
| 17 | + return self |
| 18 | + |
| 19 | + def deposit(self: TBankAccount, amount: float) -> TBankAccount: |
| 20 | + self.balance += amount |
| 21 | + return self |
| 22 | + |
| 23 | + def withdraw(self: TBankAccount, amount: float) -> TBankAccount: |
| 24 | + if self.balance >= amount: |
| 25 | + self.balance -= amount |
| 26 | + else: |
| 27 | + print("Insufficient balance") |
| 28 | + return self |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class SavingsAccount(BankAccount): |
| 33 | + interest_rate: float |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def from_application( |
| 37 | + cls: type[TBankAccount], deposit: float = 0, interest_rate: float = 1 |
| 38 | + ) -> TBankAccount: |
| 39 | + # Generate a random seven-digit bank account number |
| 40 | + account_number = random.randint(1000000, 9999999) |
| 41 | + return cls(account_number, deposit, interest_rate) |
| 42 | + |
| 43 | + def calculate_interest(self) -> float: |
| 44 | + return self.balance * self.interest_rate / 100 |
| 45 | + |
| 46 | + def add_interest(self: TBankAccount) -> TBankAccount: |
| 47 | + self.deposit(self.calculate_interest()) |
| 48 | + return self |
| 49 | + |
| 50 | + |
| 51 | +account = BankAccount(account_number=1534899324, balance=50) |
| 52 | +( |
| 53 | + account.display_balance() |
| 54 | + .deposit(50) |
| 55 | + .display_balance() |
| 56 | + .withdraw(30) |
| 57 | + .display_balance() |
| 58 | +) |
| 59 | + |
| 60 | +savings = SavingsAccount.from_application(deposit=100, interest_rate=5) |
| 61 | +( |
| 62 | + savings.display_balance() |
| 63 | + .add_interest() |
| 64 | + .display_balance() |
| 65 | + .deposit(50) |
| 66 | + .display_balance() |
| 67 | + .withdraw(30) |
| 68 | + .add_interest() |
| 69 | + .display_balance() |
| 70 | +) |
0 commit comments