# =========================================================
# =========== Python OOP - Bank Account Project ===========
# =========================================================
# Custom exception for handling balance-related issues.
class BalanceException(Exception):
pass
# Define the BankAccount class.
class BankAccount:
# Constant Values
min_balance = 200
min_transaction = 20
max_transaction = 100000
def __init__(self, acc_name, initial_amount):
# Validate account name
if not isinstance(acc_name, str) or len(acc_name.strip()) == 0:
raise ValueError("Account name must be a non-empty string.")
# Validate initial amount
if not isinstance(initial_amount, (int, float)) or initial_amount < self.min_balance:
raise ValueError("Initial amount must be a number and at least $200.")
# Initialize account with a name and initial balance.
self.name = acc_name
self.balance = initial_amount
print(
f"\nAccount Created Successfully ✔💸\nAccount Name = {self.name} ==> Account Balance = ${self.balance:.2f}")
# String representation of the account (User Friendly)
def __str__(self):
return f"\n[Account Name = {self.name} , Account Balance = ${self.balance:.2f}]"
# Official representation of the account. (Developers)
def __repr__(self):
return f"\nBank Account (Account Name = {self.name} , Account Balance = ${self.balance:.2f} )"
# Property to get the account balance.
@property
def acc_balance(self):
return f"'{self.name}'s Account Balance = ${self.balance:.2f}"
# Setter for account balance with validation.
@acc_balance.setter
def acc_balance(self, value):
if not isinstance(value, (int, float)):
raise ValueError("Balance amount must be a number.")
self.balance = value
# Private method to validate or check transaction amounts.
def _validate_transaction(self, amount):
if not isinstance(amount, (int, float)):
raise TypeError(f"Only numbers allowed! .. you can't enter a {type(amount).__name__}.")
if amount > 100000:
raise BalanceException(f"{self.name}, the maximum deposit or withdrawal amount is ${self.max_transaction}.")
if self.balance < amount:
raise BalanceException(f"Sorry, {self.name} .. You only have ${self.balance:.2f} in your balance.")
if amount < 20:
raise BalanceException(f"{self.name}, the minimum deposit or withdrawal amount is ${self.min_transaction}.")
# Method to handle deposits.
def deposit(self, amount):
try:
self._validate_transaction(amount)
self.balance += amount
print("\nDeposit Completed Successfully ✅")
print(self.acc_balance)
except (BalanceException, ValueError, TypeError) as error:
print(f"\nDeposit Interrupted ❌ : {error}")
except Exception as error:
print(f"\nAn unexpected error occurred ! : {error}")
# Method to handle withdrawals.
def withdraw(self, amount):
try:
self._validate_transaction(amount)
self.balance -= amount
print("\nWithdraw Completed Successfully ✅")
print(self.acc_balance)
except (BalanceException, ValueError, TypeError) as error:
print(f"\nWithdraw Interrupted ❌ : {error}")
except Exception as error:
print(f"\nAn unexpected error occurred ! : {error}")
# Method to handle transfers between accounts.
def transfer(self, amount, account):
try:
print("========== Beginning Transfer... 🚀 ==========")
self._validate_transaction(amount)
self.withdraw(amount) # Withdraw from account (a)
account.deposit(amount) # Deposit withdraw into account (b)
except (BalanceException, ValueError, TypeError) as error:
print(f"\nTransfer Interrupted ❌ : {error}")
except Exception as error:
print(f"\nAn unexpected error occurred ! : {error}")
else:
# If no exceptions happened.
print(f"\nTransfer Completed Successfully 🔄✅")
finally:
# Always show the final balances after a transfer.
print(f"\nFinal Balances:\n{self.acc_balance}\n{account.acc_balance}")
# Subclass for an interest-bearing account (Riba Account).
class InterestRewardsAcc(BankAccount):
interest_rate = 0.05 # Fixed 5% interest for deposits.
# Overriding Deposit method to add interest.
def deposit(self, amount):
try:
self._validate_transaction(amount)
self.balance += (amount * (1 + self.interest_rate))
print("\nDeposit Completed Successfully ✅")
print(self.acc_balance)
except (BalanceException, ValueError, TypeError) as error:
print(f"\nDeposit Interrupted ❌ : {error}")
except Exception as error:
print(f"\nAn unexpected error occurred ! : {error}")
# Subclass for a savings account with a withdrawal fee.
class SavingsAccount(InterestRewardsAcc):
fee = 5 # Fixed fee for withdrawals.
# Overriding Withdraw method to include the fee.
def withdraw(self, amount):
try:
self._validate_transaction(amount)
self.balance -= (amount + self.fee)
print("\nWithdraw Completed Successfully ✅")
print(f"{self.acc_balance}\n- A ${self.fee} fee was deducted from your balance.")
except (BalanceException, ValueError, TypeError) as error:
print(f"\nWithdraw Interrupted ❌ : {error}")
except Exception as error:
print(f"\nAn unexpected error occurred ! : {error}")
السلام عليكم ورحمة الله قمت بعمل هذا المشروع بعد الانتهاء من دروس الOOP في بايثون وأخذ مني وقت طويل والكثير من البحث والتعديل، فما رأيكم بالنسبة لمبتدئ وما نصائحكم مستقبلاً جزاكم الله خيرا