## دالة __init__ وكلمة self
### __init__: Constructor دالة خاصة تُستدعى تلقائياً عند إنشاء كائن جديد.
```python class Person: def __init__(self, name, age): # هنا تُحدَّد خصائص الكائن self.name = name # instance attribute self.age = age ```
### self: مرجع الكائن - **self** يُشير إلى الكائن الحالي - يجب أن يكون المعامل الأول في كل method - يمكن تسميته أي شيء لكن self هو الاتفاق
### الفرق بين Class و Instance Attributes: ```python class Counter: count = 0 # class attribute (مشترك) def __init__(self): self.value = 0 # instance attribute (خاص بكل كائن) ```
| 1 | class BankAccount: |
| 2 | bank_name = "بنك الأهلي" # مشترك |
| 3 | |
| 4 | def __init__(self, owner, balance=0): |
| 5 | self.owner = owner # خاص بكل حساب |
| 6 | self.balance = balance |
| 7 | self.transactions = [] # خاص بكل حساب |
| 8 | |
| 9 | def deposit(self, amount): |
| 10 | self.balance += amount |
| 11 | self.transactions.append(f"+{amount}") |
| 12 | |
| 13 | def withdraw(self, amount): |
| 14 | if amount <= self.balance: |
| 15 | self.balance -= amount |
| 16 | self.transactions.append(f"-{amount}") |
| 17 | else: |
| 18 | print("رصيد غير كافٍ") |
| 19 | |
| 20 | def get_info(self): |
| 21 | return f"{self.owner}: {self.balance} جنيه" |
مثال 1: تطبيق حساب بنكي
| 1 | class BankAccount: |
| 2 | def __init__(self, owner, balance=0): |
| 3 | self.owner = owner |
| 4 | self.balance = balance |
| 5 | |
| 6 | def deposit(self, amount): |
| 7 | self.balance += amount |
| 8 | print(f"تم إيداع {amount}. الرصيد: {self.balance}") |
| 9 | |
| 10 | def withdraw(self, amount): |
| 11 | if amount <= self.balance: |
| 12 | self.balance -= amount |
| 13 | print(f"تم سحب {amount}. الرصيد: {self.balance}") |
| 14 | else: |
| 15 | print("رصيد غير كافٍ!") |
| 16 | |
| 17 | def __str__(self): |
| 18 | return f"حساب {self.owner}: {self.balance} جنيه" |
| 19 | |
| 20 | acc = BankAccount("أحمد", 1000) |
| 21 | acc.deposit(500) |
| 22 | acc.withdraw(200) |
| 23 | print(acc) |