# =========================================================# =========== Python OOP - Bank Account Project ===========# =========================================================# Custom exception for handling balance-related issues.classBalanceException(Exception):pass# Define the BankAccount class.classBankAccount:# Constant Values
min_balance =200
min_transaction =20
max_transaction =100000def __init__(self, acc_name, initial_amount):# Validate account nameifnot isinstance(acc_name, str)or len(acc_name.strip())==0:raiseValueError("Account name must be a non-empty string.")# Validate initial amountifnot isinstance(initial_amount,(int, float))or initial_amount < self.min_balance:raiseValueError("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.@propertydef 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):ifnot isinstance(value,(int, float)):raiseValueError("Balance amount must be a number.")
self.balance = value
# Private method to validate or check transaction amounts.def _validate_transaction(self, amount):ifnot isinstance(amount,(int, float)):raiseTypeError(f"Only numbers allowed! .. you can't enter a {type(amount).__name__}.")if amount >100000:raiseBalanceException(f"{self.name}, the maximum deposit or withdrawal amount is ${self.max_transaction}.")if self.balance < amount:raiseBalanceException(f"Sorry, {self.name} .. You only have ${self.balance:.2f} in your balance.")if amount <20:raiseBalanceException(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}")exceptExceptionas 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}")exceptExceptionas 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}")exceptExceptionas 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).classInterestRewardsAcc(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}")exceptExceptionas error:print(f"\nAn unexpected error occurred ! : {error}")# Subclass for a savings account with a withdrawal fee.classSavingsAccount(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}")exceptExceptionas error:print(f"\nAn unexpected error occurred ! : {error}")
السلام عليكم ورحمة الله قمت بعمل هذا المشروع بعد الانتهاء من دروس الOOP في بايثون وأخذ مني وقت طويل والكثير من البحث والتعديل، فما رأيكم بالنسبة لمبتدئ وما نصائحكم مستقبلاً جزاكم الله خيرا
السؤال
Khaled Soudy
السلام عليكم ورحمة الله قمت بعمل هذا المشروع بعد الانتهاء من دروس الOOP في بايثون وأخذ مني وقت طويل والكثير من البحث والتعديل، فما رأيكم بالنسبة لمبتدئ وما نصائحكم مستقبلاً جزاكم الله خيرا
رابط هذا التعليق
شارك على الشبكات الإجتماعية
0 أجوبة على هذا السؤال
Recommended Posts
انضم إلى النقاش
يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.