دروس الوحدة (1/4)
الطبقات والحالات
الفئة عبارة عن مخطط لإنشاء كائنات تحتوي على بيانات (سمات) والسلوك (الأساليب). المثيل هو كائن ملموس تم إنشاؤه منه الفصل.
الحد الأدنى من بناء الجملة
class Cane:
def __init__(self, nome, eta):
self.nome = nome
self.eta = eta
def abbaia(self):
return f"{self.nome} dice WOOF!"
# creazione di istanze
fido = Cane("Fido", 3)
luna = Cane("Luna", 5)
fido.nome # 'Fido'
fido.abbaia() # 'Fido dice WOOF!'__init__: "المنشئ"
يتم استدعاء الأسلوب __init__ ** تلقائيًا ** عند إنشاء ملف
مثيل (Cane("Fido", 3)). يتم استخدامه لتهيئة السمات.
من الناحية الفنية، فهو ليس منشئًا (تم إنشاء الكائن بالفعل بواسطة
__new__)، ولكنه المكان الذي قمت بتعيين الحالة الأولية فيه.
self: المعلمة الأولى
self هو المرجع للمثيل الذي تم استدعاء الطريقة عليه. إنه أ
اصطلاح (ليست كلمة رئيسية) وهي المعلمة الأولى دائمًا** للمثيل
طرق.
fido.abbaia()
# equivalente a Cane.abbaia(fido)
# Python passa fido come self automaticamenteمثيل مقابل سمات الفئة
class Cane:
specie = "Canis familiaris" # attributo di CLASSE (condiviso)
def __init__(self, nome):
self.nome = nome # attributo di ISTANZA (per ognuno)
fido = Cane("Fido")
luna = Cane("Luna")
fido.nome # 'Fido' (istanza)
luna.nome # 'Luna' (istanza)
fido.specie # 'Canis familiaris' (cercato sulla classe)
Cane.specie # 'Canis familiaris'طرق متعددة والدولة
class Contatore:
def __init__(self, inizio=0):
self.valore = inizio
def incrementa(self, di=1):
self.valore += di
def reset(self):
self.valore = 0
c = Contatore()
c.incrementa()
c.incrementa(di=5)
c.valore # 6
c.reset()
c.valore # 0دورك
حدد فئة `Point` باستخدام __init__(self, x, y) الذي يخزن السمات. أضف طريقة "distance_from_origin" التي تُرجع الجذر التربيعي لـ x^2 + y^2. أنشئ `p = Point(3, 4)` وقم بتقييم `p.distance_from_origin()`.
إظهار التلميح
math.sqrt(self.x ** 2 + self.y ** 2)
الحل متاح بعد 3 من المحاولات
تمرين المراجعة
حدد `الحساب البنكي` باستخدام __init__(self, Balance=0) والطرق `deposit(amount)`، `withdraw(amount)` التي تعدل الرصيد الذاتي. أنشئ `a = BankAccount(100)`، أودع 50، واسحب 30. قم بتقييم `a.balance`.
إظهار التلميح
self.balance += المبلغ المودع.
الحل متاح بعد 3 من المحاولات
التحدي الإضافي
Define a class `Rectangle` with a constructor `__init__(self, width, height)` to set width and height, and a method `area(self)` that returns the product of width and height. Instantiate a rectangle with width `4` and height `5` storing it in `rect`, and evaluate `rect.area()`.
إظهار التلميح
تذكر أن تستخدم self للوصول إلى السمات الموجودة داخل المنطقة (الذات).
الحل متاح بعد 3 من المحاولات