__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
תרגילים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?
כתבו 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?
מדף, צעד 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
כתבו 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?