التعامل مع دوال الكائنات
دوال الكائنات (Instance methods) هي دوال معرفة داخل الفئة وتعمل على البيانات المحددة لكائن معين.
الوصول إلى self وتعديله
تستخدم الدوال مرجع self لقراءة أو تغيير خصائص الكائن.
python class Account: def init(self, owner, balance): self.owner = owner self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Transaction failed: Insufficient funds.")
return False
self.balance -= amount
print(f"Withdrew ${amount}. Remaining balance: ${self.balance}")
return True
استخدام الفئة
my_account = Account('Smith', 500)
my_account.deposit(200) # الرصيد أصبح 700 my_account.withdraw(100) # الرصيد أصبح 600 my_account.withdraw(1000) # يفشل