דילוג לתוכן המרכזי
מודול 7 · שיעור 1 מתוך 425/36 בקורס~14 min
שיעורי מודול (1/4)

שיעורים ומופעים

מחלקה היא תוכנית ליצירת אובייקטים בעלי נתונים (תכונות) והתנהגות (שיטות). מופע הוא אובייקט קונקרטי שנוצר ממנו הכיתה.

תחביר מינימלי

Python
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 היא ההתייחסות למופע שבו נקראה השיטה. זה א מוסכמה (לא מילת מפתח) והיא תמיד הפרמטר הראשון של דוגמה שיטות.

Python
fido.abbaia()
# equivalente a Cane.abbaia(fido)
# Python passa fido come self automaticamente

מופע לעומת תכונות מחלקה

Python
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'

מספר שיטות ומצבים

Python
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

התור שלך

פעילות גופנית#python.m7.l1.e1
ניסיונות: 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 ניסיונות

סקירת התרגיל

פעילות גופנית#python.m7.l1.e2
ניסיונות: 0טוען...

הגדר `BankAccount` עם __init__(self, balance=0) ושיטות `deposit(amount)`, `draw(amount)` שמשנות את self.balance. צור `a = BankAccount(100)`, הפקד 50, משך 30. הערך `a.balance`.

טוען עורך...
הצג רמז

self.balance += סכום בפיקדון.

הפתרון זמין לאחר 3 ניסיונות

אתגר נוסף

פעילות גופנית#python.m7.l1.e3
ניסיונות: 0טוען...

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 ניסיונות