מחלקת בסיס, super(), דריסת מתודות והרכבה מול ירושה.
Base classes, super(), overriding methods and composition vs inheritance.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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
חיות מדברותTalking animals
כתבו Animal עם name ומתודה speak() שמחזירה "...". צרו Dog ו-Cat שיורשות ודורסות את speak ("Woof", "Meow"). הדפיסו name: sound לכל חיה ברשימה.
Write Animal with name and a speak() method returning "...". Create Dog and Cat that inherit and override speak ("Woof", "Meow"). Print name: sound for each animal in a list.
איך הפלט אמור להיראות?What should the output look like?
Rex: Woof
Tom: Meow
Fish: ...
main.py
רמזHint 1:class Dog(Animal): ובתוכה רק speak.class Dog(Animal): with only speak inside.
כתבו Shape עם area() שמחזירה 0 ו-describe() שמחזירה "<ClassName> with area <area>" (השתמשו ב-type(self).__name__). צרו Square(side) ו-Circle(r) (שטח עיגול: round(3.14159 * r * r, 2)). הדפיסו describe לשתיהן.
Write Shape with area() returning 0 and describe() returning "<ClassName> with area <area>" (use type(self).__name__). Create Square(side) and Circle(r) (circle area: round(3.14159 * r * r, 2)). Print describe for both.
איך הפלט אמור להיראות?What should the output look like?
Square with area 9
Circle with area 3.14
main.py
רמזHint 1:describe נכתבת פעם אחת באב בלבד.describe is written once, in the parent only.
רמזHint 2:כל בן דורס רק את area.Each child overrides only area.
נתונה Counter עם tick(). כתבו LimitedCounter(limit) שיורשת ודורסת את tick: אם הגענו ל-limit, לא מגדילים ומחזירים False; אחרת קוראים ל-super().tick() ומחזירים True.
Given Counter with tick(). Write LimitedCounter(limit) that inherits and overrides tick: at the limit it doesn't increase and returns False; otherwise it calls super().tick() and returns True.
איך הפלט אמור להיראות?What should the output look like?
[True, True, False, False] 2
main.py
רמזHint 1:בבנאי: super().__init__() ואז self.limit = limit.In the constructor: super().__init__() then self.limit = limit.
מדף, צעד 16: EBook ו-AudioBookShelf, step 16: EBook and AudioBook
פרויקט מלווהCompanion project
ל-Book(title, author) יש label() שמחזירה "title by author". צרו EBook(title, author, mb) ו-AudioBook(title, author, minutes) שקוראות ל-super ודורסות את label: "Dune by Frank Herbert [2.5 MB]" ו-"Emma by Jane Austen [12h 30m]". הדפיסו label לכל ספר במדף.
Book(title, author) has label() returning "title by author". Create EBook(title, author, mb) and AudioBook(title, author, minutes) that call super and override label: "Dune by Frank Herbert [2.5 MB]" and "Emma by Jane Austen [12h 30m]". Print label for each book on the shelf.
איך הפלט אמור להיראות?What should the output look like?
Matilda by Roald Dahl
Dune by Frank Herbert [2.5 MB]
Emma by Jane Austen [12h 30m]
כתבו Notifier עם send(msg) שמחזירה format(msg), ו-format שמחזירה את msg. צרו EmailNotifier(address) ("To <address>: <msg>"), SMSNotifier(phone) (מקצר ל-20 תווים: "SMS <phone>: <msg[:20]>") ו-LoudNotifier שיורשת מ-EmailNotifier ומחזירה את התוצאה של האב באותיות גדולות. הפונקציה broadcast(notifiers, msg) מחזירה רשימת תוצאות.
Write Notifier with send(msg) returning format(msg), and format returning msg. Create EmailNotifier(address) ("To <address>: <msg>"), SMSNotifier(phone) (trims to 20 chars: "SMS <phone>: <msg[:20]>") and LoudNotifier inheriting from EmailNotifier that returns the parent's result in capitals. broadcast(notifiers, msg) returns a list of results.
איך הפלט אמור להיראות?What should the output look like?
To noa@example.com: Your book is due back tomorrow
SMS 050: Your book is due bac
TO DAN@EXAMPLE.COM: YOUR BOOK IS DUE BACK TOMORROW
main.py
רמזHint 1:רק format נדרסת. send נשארת באב.Only format is overridden. send stays in the parent.
כתבו count_by_type(items) שמחזירה מילון: לכל מחלקה בשרשרת הירושה של כל פריט (חוץ מ-object), כמה פריטים הם מופע שלה. השתמשו ב-type(item).__mro__. לדוגמה, Comic נספר גם תחת Book וגם תחת Media.
Write count_by_type(items) returning a dict: for every class in each item's inheritance chain (except object), how many items are an instance of it. Use type(item).__mro__. For example, a Comic counts under Book and Media too.
איך הפלט אמור להיראות?What should the output look like?
{'Book': 3, 'Media': 4, 'Comic': 2, 'Film': 1}
main.py
רמזHint 1:לולאה על type(it).__mro__, ודילוג על object.Loop over type(it).__mro__, skipping object.