ירושהInheritance
מחלקת בסיס, super(), דריסת מתודות והרכבה מול ירושה.
Base classes, super(), overriding methods and composition vs inheritance.
חיות מדברותTalking animals
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for a in [Dog("Rex"), Cat("Tom"), Animal("Fish")]:
print(f"{a.name}: {a.speak()}")Rex: Woof Tom: Meow Fish: ...
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עובדים ומנהליםEmployees and managers
תזכורת: מה ביקשוReminder: the task
כתבו Employee(name, salary) עם pay() שמחזירה את המשכורת. Manager(name, salary, bonus) יורשת, קוראת ל-super, ודורסת את pay כך שתחזיר משכורת + בונוס (בעזרת super().pay()).
Write Employee(name, salary) with pay() returning the salary. Manager(name, salary, bonus) inherits, calls super, and overrides pay to return salary + bonus (using super().pay()).
הפתרון המלא והפלט שלוFull solution and its output
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def pay(self):
return self.salary
class Manager(Employee):
def __init__(self, name, salary, bonus):
super().__init__(name, salary)
self.bonus = bonus
def pay(self):
return super().pay() + self.bonus
team = [Employee("Dana", 9000), Manager("Avi", 12000, 3000)]
print(sum(p.pay() for p in team))24000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צורותShapes
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
class Shape:
def area(self):
return 0
def describe(self):
return f"{type(self).__name__} with area {self.area()}"
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return round(3.14159 * self.r * self.r, 2)
for s in [Square(3), Circle(1)]:
print(s.describe())Square with area 9 Circle with area 3.14
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מונה מיוחדA special counter
תזכורת: מה ביקשוReminder: the task
נתונה 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.
הפתרון המלא והפלט שלוFull solution and its output
class Counter:
def __init__(self):
self.n = 0
def tick(self):
self.n += 1
class LimitedCounter(Counter):
def __init__(self, limit):
super().__init__()
self.limit = limit
def tick(self):
if self.n >= self.limit:
return False
super().tick()
return True
c = LimitedCounter(2)
print([c.tick() for _ in range(4)], c.n)[True, True, False, False] 2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 16: EBook ו-AudioBookShelf, step 16: EBook and AudioBook
תזכורת: מה ביקשוReminder: the task
ל-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.
הפתרון המלא והפלט שלוFull solution and its output
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def label(self):
return f"{self.title} by {self.author}"
class EBook(Book):
def __init__(self, title, author, mb):
super().__init__(title, author)
self.mb = mb
def label(self):
return super().label() + f" [{self.mb} MB]"
class AudioBook(Book):
def __init__(self, title, author, minutes):
super().__init__(title, author)
self.minutes = minutes
def label(self):
h, m = divmod(self.minutes, 60)
return super().label() + f" [{h}h {m}m]"
shelf = [Book("Matilda", "Roald Dahl"), EBook("Dune", "Frank Herbert", 2.5), AudioBook("Emma", "Jane Austen", 750)]
for b in shelf:
print(b.label())Matilda by Roald Dahl Dune by Frank Herbert [2.5 MB] Emma by Jane Austen [12h 30m]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מערכת התראותA notification system
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
class Notifier:
def send(self, msg):
return self.format(msg)
def format(self, msg):
return msg
class EmailNotifier(Notifier):
def __init__(self, address):
self.address = address
def format(self, msg):
return f"To {self.address}: {msg}"
class SMSNotifier(Notifier):
def __init__(self, phone):
self.phone = phone
def format(self, msg):
return f"SMS {self.phone}: {msg[:20]}"
class LoudNotifier(EmailNotifier):
def format(self, msg):
return super().format(msg).upper()
def broadcast(notifiers, msg):
return [n.send(msg) for n in notifiers]
for line in broadcast([EmailNotifier("noa@example.com"), SMSNotifier("050"), LoudNotifier("dan@example.com")], "Your book is due back tomorrow"):
print(line)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
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ספירת עץCounting the tree
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
class Media:
pass
class Book(Media):
pass
class Comic(Book):
pass
class Film(Media):
pass
def count_by_type(items):
counts = {}
for it in items:
for k in type(it).__mro__:
if k is object:
continue
counts[k.__name__] = counts.get(k.__name__, 0) + 1
return counts
print(count_by_type([Book(), Comic(), Film(), Comic()])){'Book': 3, 'Media': 4, 'Comic': 2, 'Film': 1}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.