נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
15
חלקPart 3: קוד נקי ו-OOPClean code & OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

מחלקות ואובייקטיםClasses & objects

class, __init__, self, תכונות ומתודות.

class, __init__, self, attributes and methods.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה הוא self במתודה?What is self in a method?

2. מה ידפיס הקוד?What does this print?
python
class C:
    def __init__(self):
        self.n = 1

a = C()
b = a
b.n += 1
print(a.n, b.n)

3. מתי רץ __init__?When does __init__ run?

תרגיליםExercises

תרגילExercise 1

מחלקת כלבA Dog class

כתבו מחלקה Dog עם name ו-sound (ברירת מחדל "Woof"), ומתודה speak() שמחזירה "<name> says <sound>". צרו את Rex והדפיסו את מה שהוא אומר.

Write a Dog class with name and sound (default "Woof"), and a speak() method returning "<name> says <sound>". Create Rex and print what he says.

איך הפלט אמור להיראות?What should the output look like?
Rex says Woof
main.py
רמזHint 1: def __init__(self, name, sound="Woof"):def __init__(self, name, sound="Woof"):
רמזHint 2: return f"{self.name} says {self.sound}"return f"{self.name} says {self.sound}"
לפתרוןSolution
תרגילExercise 2

חשבון בנקA bank account

כתבו Account עם owner ו-balance שמתחיל ב-0. deposit(x) מוסיפה, withdraw(x) מורידה רק אם יש מספיק ומחזירה True, אחרת מחזירה False ולא משנה דבר.

Write Account with owner and balance starting at 0. deposit(x) adds, withdraw(x) subtracts only if there's enough and returns True, otherwise returns False and changes nothing.

איך הפלט אמור להיראות?What should the output look like?
True False 70
main.py
רמזHint 1: ב-withdraw: if x > self.balance: return False.In withdraw: if x > self.balance: return False.
רמזHint 2: אחרי ההורדה: return True.After subtracting: return True.
לפתרוןSolution
תרגילExercise 3

מלבןA rectangle

כתבו Rect(w, h) עם מתודות area(), perimeter() ו-is_square(). הדפיסו את שלושתן עבור Rect(3, 4).

Write Rect(w, h) with methods area(), perimeter() and is_square(). Print all three for Rect(3, 4).

איך הפלט אמור להיראות?What should the output look like?
12 14 False
main.py
רמזHint 1: שטח: self.w * self.h.Area: self.w * self.h.
רמזHint 2: היקף: 2 * (self.w + self.h).Perimeter: 2 * (self.w + self.h).
לפתרוןSolution
תרגילExercise 4

רשימת קניותA shopping list

כתבו ShoppingList עם add(item, qty=1) (אם הפריט קיים, מגדילים כמות), remove(item), ו-total_items() שמחזירה את סך הכמויות. שמרו את הפריטים במילון self.items.

Write ShoppingList with add(item, qty=1) (if it exists, increase the quantity), remove(item), and total_items() returning the sum of quantities. Keep items in a dict self.items.

איך הפלט אמור להיראות?What should the output look like?
{'milk': 3, 'eggs': 12} 15
main.py
רמזHint 1: self.items[item] = self.items.get(item, 0) + qtyself.items[item] = self.items.get(item, 0) + qty
רמזHint 2: self.items.pop(item, None) לא נופל אם אין פריט.self.items.pop(item, None) doesn't crash if missing.
לפתרוןSolution
תרגילExercise 5

מדף, צעד 15: Book ו-LibraryShelf, step 15: Book and Library

פרויקט מלווהCompanion project

הפכו את המדף למחלקות. Book(title, author, pages) עם read שמתחיל ב-0 ומתודה read_pages(n) (לא עוברים את pages). Library עם add(book), find(title) (בלי רגישות לאותיות גדולות, או None), ו-unread() שמחזירה רשימת כותרות של ספרים שלא התחילו.

Turn the shelf into classes. Book(title, author, pages) with read starting at 0 and a read_pages(n) method (never past pages). Library with add(book), find(title) (case-insensitive, or None), and unread() returning titles of books not started.

איך הפלט אמור להיראות?What should the output look like?
['Emma']
shelf.py
רמזHint 1: self.read = min(self.read + n, self.pages)self.read = min(self.read + n, self.pages)
רמזHint 2: [b.title for b in self.books if b.read == 0][b.title for b in self.books if b.read == 0]
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

מחסניתA stack

כתבו Stack עם push(x), pop() (מחזירה את האחרון ומוציאה; על מחסנית ריקה מחזירה None), peek() (מחזירה בלי להוציא), is_empty() ו-size(). השתמשו בה כדי לבדוק אם הסוגריים במחרוזת מאוזנים: balanced("(a[b]{c})") → True.

Write Stack with push(x), pop() (returns and removes the last; on an empty stack returns None), peek() (returns without removing), is_empty() and size(). Use it to check whether brackets in a string are balanced: balanced("(a[b]{c})") → True.

איך הפלט אמור להיראות?What should the output look like?
True False False
main.py
רמזHint 1: פותחים → push. סוגרים → pop ובדיקה שהזוג מתאים.Opening → push. Closing → pop and check the pair matches.
רמזHint 2: בסוף המחסנית חייבת להיות ריקה.At the end the stack must be empty.
לפתרוןSolution
אתגרChallenge 2

טיימר משימותA task timer

כתבו Task(name) עם log(minutes) שמוסיפה זמן, ו-Tracker שמחזיקה משימות: start(name) יוצרת משימה אם אין (ומחזירה אותה), total() מחזירה את כל הדקות, ו-top() מחזירה את שם המשימה עם הכי הרבה דקות.

Write Task(name) with log(minutes) adding time, and Tracker holding tasks: start(name) creates the task if missing (and returns it), total() returns all minutes, top() returns the name of the task with the most minutes.

איך הפלט אמור להיראות?What should the output look like?
100 read
main.py
רמזHint 1: שמרו מילון name → Task.Keep a dict name → Task.
רמזHint 2: max(self.tasks.values(), key=lambda t: t.minutes).namemax(self.tasks.values(), key=lambda t: t.minutes).name
לפתרוןSolution

נבנה על ידיBuilt by Ariel Yohimovich