שיעורי מודול (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התור שלך
הגדר מחלקה 'נקודה' עם __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 ניסיונות
סקירת התרגיל
הגדר `BankAccount` עם __init__(self, balance=0) ושיטות `deposit(amount)`, `draw(amount)` שמשנות את self.balance. צור `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()`.
הצג רמז
זכור להשתמש בעצמי כדי לגשת לתכונות בתוך אזור (עצמי).
הפתרון זמין לאחר 3 ניסיונות