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

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

Dunder methodsDunder methods

__str__, __repr__, __eq__, __lt__, __len__ ומה הם נותנים.

__str__, __repr__, __eq__, __lt__, __len__ and what they give you.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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. מה פייתון קוראת כשכותבים print(book)?What does Python call for print(book)?

2. מה ידפיס?What prints?
python
class P:
    def __init__(self, x):
        self.x = x

print(P(1) == P(1))

3. איזו מתודה מאפשרת for b in shelf?Which method enables for b in shelf?

תרגיליםExercises

תרגילExercise 1

נקודה מודפסתA printable point

כתבו Point(x, y) עם __str__ שמחזירה (x, y) ו-__repr__ שמחזירה Point(x=1, y=2). הדפיסו נקודה ואת הרשימה [Point(1, 2)].

Write Point(x, y) with __str__ returning (x, y) and __repr__ returning Point(x=1, y=2). Print a point and the list [Point(1, 2)].

איך הפלט אמור להיראות?What should the output look like?
(1, 2)
[Point(x=1, y=2)]
main.py
רמזHint 1: return f"({self.x}, {self.y})"return f"({self.x}, {self.y})"
רמזHint 2: רשימה מדפיסה repr של כל פריט.A list prints each item's repr.
לפתרוןSolution
תרגילExercise 2

כסף שווהEqual money

כתבו Money(amount, currency) עם __eq__ (שווה אם הסכום והמטבע זהים; לסוג אחר NotImplemented) ו-__add__ שמחברת רק אותו מטבע (אחרת ValueError).

Write Money(amount, currency) with __eq__ (equal when amount and currency match; NotImplemented for other types) and __add__ that adds only the same currency (otherwise ValueError).

איך הפלט אמור להיראות?What should the output look like?
True
main.py
רמזHint 1: if self.currency != other.currency: raise ValueError(...)if self.currency != other.currency: raise ValueError(...)
רמזHint 2: return Money(self.amount + other.amount, self.currency)return Money(self.amount + other.amount, self.currency)
לפתרוןSolution
תרגילExercise 3

שחקנים ממויניםSorted players

כתבו Player(name, score) עם __lt__ לפי ניקוד ו-__repr__ שמחזירה name:score. הדפיסו את הרשימה ממוינת מהגבוה לנמוך (sorted(..., reverse=True)).

Write Player(name, score) with __lt__ by score and __repr__ returning name:score. Print the list sorted high to low (sorted(..., reverse=True)).

איך הפלט אמור להיראות?What should the output look like?
[Avi:95, Dana:82, Noa:70]
main.py
רמזHint 1: return self.score < other.scorereturn self.score < other.score
רמזHint 2: return f"{self.name}:{self.score}"return f"{self.name}:{self.score}"
לפתרוןSolution
תרגילExercise 4

פלייליסטA playlist

כתבו Playlist עם add(song), __len__, __contains__ (בלי רגישות לאותיות גדולות), __iter__ ו-__getitem__(i) שמחזירה את השיר במקום i (כך p[0] עובד).

Write Playlist with add(song), __len__, __contains__ (case-insensitive), __iter__ and __getitem__(i) returning the song at index i (so p[0] works).

איך הפלט אמור להיראות?What should the output look like?
3 True Yellow Dynamite ['Yellow', 'Hello', 'Dynamite']
main.py
רמזHint 1: return self.songs[i]return self.songs[i]
רמזHint 2: return iter(self.songs)return iter(self.songs)
לפתרוןSolution
תרגילExercise 5

מדף, צעד 17: ספרים מתנהגים יפהShelf, step 17: well-behaved books

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

הוסיפו ל-Book(title, author, pages): __str__ ("Dune by Frank Herbert"), __repr__ ("Book('Dune', 412)"), __eq__ (כותרת וסופר, בלי רגישות לאותיות גדולות) ו-__lt__ (לפי כותרת). ל-Library הוסיפו __len__, __iter__ ו-__contains__ (מקבלת Book). הדפיסו את הספרייה ממוינת.

Add to Book(title, author, pages): __str__ ("Dune by Frank Herbert"), __repr__ ("Book('Dune', 412)"), __eq__ (title and author, case-insensitive) and __lt__ (by title). Add __len__, __iter__ and __contains__ (takes a Book) to Library. Print the library sorted.

איך הפלט אמור להיראות?What should the output look like?
2 True
[Book('Dune', 412), Book('Matilda', 240)]
Dune by Frank Herbert
Matilda by Roald Dahl
shelf.py
רמזHint 1: __eq__: (self.title.lower(), self.author.lower()) == (...)__eq__: (self.title.lower(), self.author.lower()) == (...)
רמזHint 2: __contains__: return book in self.books (משתמש ב-__eq__!)__contains__: return book in self.books (uses __eq__!)
לפתרוןSolution

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

אתגרChallenge 1

וקטורA vector

כתבו Vector(x, y) עם __add__, __sub__, __mul__ (כפל בסקלר: v * 3), __rmul__ (כדי ש-3 * v יעבוד), __eq__, __abs__ (אורך, מעוגל ל-2) ו-__repr__ (Vector(1, 2)).

Write Vector(x, y) with __add__, __sub__, __mul__ (scalar: v * 3), __rmul__ (so 3 * v works), __eq__, __abs__ (length, rounded to 2) and __repr__ (Vector(1, 2)).

איך הפלט אמור להיראות?What should the output look like?
Vector(4, 5) Vector(2, 3) Vector(6, 8) 5.0
main.py
רמזHint 1: __rmul__ יכולה פשוט להחזיר self * k.__rmul__ can just return self * k.
רמזHint 2: אורך: round((self.x ** 2 + self.y ** 2) ** 0.5, 2)Length: round((self.x ** 2 + self.y ** 2) ** 0.5, 2)
לפתרוןSolution
אתגרChallenge 2

טווח תאריכיםA date range

כתבו DayRange(start, end) (מספרי ימים, כולל שניהם) שמתנהגת כמו range: len, in (מספר בטווח), לולאת for, ו-__getitem__ שתומכת באינדקס שלילי ומעלה IndexError מחוץ לטווח. DayRange(3, 7) מכיל 5 ימים.

Write DayRange(start, end) (day numbers, both inclusive) that behaves like range: len, in (a number in range), a for loop, and __getitem__ supporting negative indexes and raising IndexError outside the range. DayRange(3, 7) has 5 days.

איך הפלט אמור להיראות?What should the output look like?
5 True False [3, 4, 5, 6, 7] 3 7
main.py
רמזHint 1: len: self.end - self.start + 1.len: self.end - self.start + 1.
רמזHint 2: באינדקס שלילי: i += len(self) ואז בודקים גבולות.Negative index: i += len(self) then check bounds.
לפתרוןSolution

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