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

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

ירושהInheritance

מחלקת בסיס, super(), דריסת מתודות והרכבה מול ירושה.

Base classes, super(), overriding methods and composition vs inheritance.

01ירושה בסיסיתBasic inheritance

לפעמים יש כמה סוגים של אותו דבר: ספר מודפס, ספר דיגיטלי, ספר שמע. כולם ספרים, אבל לכל אחד פרט משלו. ירושה מאפשרת לכתוב את המשותף פעם אחת במחלקת האב, וכל מחלקת בן מוסיפה רק את מה שמיוחד לה.

Sometimes there are several kinds of the same thing: a printed book, an e-book, an audiobook. All are books, but each has its own detail. Inheritance lets you write what's shared once in the parent class, and each child class adds only what's special to it.

inherit.py
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 file_size(self):
        return "2 MB"

e = EBook("Dune", "Frank Herbert")
print(e.label())
print(e.file_size())
print(isinstance(e, Book), isinstance(e, EBook))
פלטOutput
Dune by Frank Herbert
2 MB
True True
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

ירושה היא כמו דגם חדש של רכב: הוא מקבל את כל מה שהיה בדגם הקודם, ומוסיף מסך גדול יותר.

Inheritance is like a new car model: it gets everything the previous model had, and adds a bigger screen.

טעות נפוצהCommon mistake

קוראים למתודה של הבן על אובייקט של האב.

Calling a child's method on a parent object.

inherit.py
class Book:
    pass

class EBook(Book):
    def file_size(self):
        return "2 MB"

b = Book()
print(b.file_size())
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/inherit.py", line 9, in <module>
    print(b.file_size())
          ^^^^^^^^^^^
AttributeError: 'Book' object has no attribute 'file_size'
בעברית פשוטה: In plain words: AttributeError: 'Book' object has no attribute 'file_size': הירושה הולכת רק מלמעלה למטה. לספר רגיל אין את מה שהוספנו ל-EBook.AttributeError: 'Book' object has no attribute 'file_size': inheritance flows only downward. A plain book doesn't have what we added to EBook.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02super() ו-__init__super() and __init__

כשלבן יש __init__ משלו, הוא מחליף את של האב. כדי שהתכונות של האב עדיין ייווצרו, קוראים ל-super(): super().__init__(title, author), ואז מוסיפים את התכונות החדשות.

When the child has its own __init__, it replaces the parent's. So the parent's attributes still get created, call super(): super().__init__(title, author), then add the new attributes.

ויזואלייזר זיכרוןMemory visualizersuper() ממלא את החלק של האבsuper() fills in the parent's part

מה קורה עכשיוWhat happens now

פלטOutput

משתנים (frames)Variables (frames)

אובייקטים בזיכרוןObjects in memory

אנלוגיה מהחייםReal-life analogy

super() הוא כמו לבנות קומה שנייה: קודם יוצקים את היסודות של הבית הקיים, ורק אז בונים מעליהם.

super() is like building a second floor: first pour the existing house's foundation, then build on top.

טעות נפוצהCommon mistake

שוכחים לקרוא ל-super().__init__.

Forgetting to call super().__init__.

audio.py
class Book:
    def __init__(self, title):
        self.title = title

class AudioBook(Book):
    def __init__(self, title, minutes):
        self.minutes = minutes

print(AudioBook("Dune", 1260).title)
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/audio.py", line 9, in <module>
    print(AudioBook("Dune", 1260).title)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'AudioBook' object has no attribute 'title'
בעברית פשוטה: In plain words: AttributeError: 'AudioBook' object has no attribute 'title': ה-__init__ של הבן החליף את של האב, ואף אחד לא יצר title. מוסיפים super().__init__(title).AttributeError: 'AudioBook' object has no attribute 'title': the child's __init__ replaced the parent's, and nobody created title. Add super().__init__(title).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

super() קורא לגרסה של ההורה, ואז מוסיפים עליה.

super() calls the parent's version, then we add to it.

עוד דוגמה: super מוסיףOne more: super adds on
example.py
class Base:
    def hello(self):
        return "hello"

class Loud(Base):
    def hello(self):
        return super().hello().upper() + "!"

print(Loud().hello())
פלטOutput
HELLO!
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03דריסת מתודותOverriding methods

דריסה היא כתיבת מתודה בשם זהה לזו של האב. פייתון מחפשת קודם בבן, ואם לא מוצאת, עולה לאב. אפשר להשתמש בתוצאה של האב עם super().label() ולהוסיף עליה.

To override is to write a method with the same name as the parent's. Python looks in the child first and, if not found, goes up to the parent. You can reuse the parent's result with super().label() and add to it.

override.py
class Book:
    def __init__(self, title):
        self.title = title

    def label(self):
        return f"Book: {self.title}"

class AudioBook(Book):
    def __init__(self, title, minutes):
        super().__init__(title)
        self.minutes = minutes

    def label(self):
        hours = self.minutes / 60
        return super().label() + f" ({hours:.1f} h audio)"

print(Book("Emma").label())
print(AudioBook("Dune", 1260).label())
פלטOutput
Book: Emma
Book: Dune (21.0 h audio)
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

דריסה היא כמו מתכון משפחתי: הבת משתמשת במתכון של סבתא, אבל מוסיפה תבלין משלה.

Overriding is like a family recipe: the daughter uses grandma's recipe but adds her own spice.

טעות נפוצהCommon mistake

שגיאת כתיב בשם המתודה, ולכן הדריסה לא קורית בכלל.

A typo in the method name, so the override never happens.

override.py
class Book:
    def label(self):
        return "book"

class EBook(Book):
    def lable(self):
        return "ebook"

assert EBook().label() == "ebook", f"got {EBook().label()!r}: the override has a typo"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/override.py", line 9, in <module>
    assert EBook().label() == "ebook", f"got {EBook().label()!r}: the override has a typo"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: got 'book': the override has a typo
בעברית פשוטה: In plain words: AssertionError: got 'book': the override has a typo: נוצרה מתודה חדשה בשם lable, ו-label של האב נשארה. בודקים שהשם זהה בדיוק.AssertionError: got 'book': the override has a typo: a new method called lable was created and the parent's label stayed. Check the name matches exactly.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

מחלקה יורשת יכולה להחליף פעולה של ההורה.

A child class can replace a parent's action.

עוד דוגמה: כל חיה וקול שלהOne more: each animal its own sound
example.py
class Animal:
    def sound(self):
        return "..."

class Cow(Animal):
    def sound(self):
        return "moo"

for a in [Animal(), Cow()]:
    print(type(a).__name__, a.sound())
פלטOutput
Animal ...
Cow moo
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04פולימורפיזםPolymorphism

כוחה האמיתי של ירושה: אפשר לשים ספרים מסוגים שונים באותה רשימה ולקרוא לכולם describe(). הלולאה לא צריכה לדעת מי מה: כל אובייקט יודע לתאר את עצמו. זה פולימורפיזם.

Inheritance's real power: put books of different kinds in one list and call describe() on all. The loop doesn't need to know who's what: each object knows how to describe itself. That's polymorphism.

poly.py
class Item:
    def __init__(self, title):
        self.title = title

    def describe(self):
        return f"{self.title}"

class Paper(Item):
    def describe(self):
        return f"{self.title} (paper)"

class Digital(Item):
    def describe(self):
        return f"{self.title} (e-book)"

class Audio(Item):
    def describe(self):
        return f"{self.title} (audio)"

shelf = [Paper("Emma"), Digital("Dune"), Audio("Matilda")]
for item in shelf:
    print(item.describe())
פלטOutput
Emma (paper)
Dune (e-book)
Matilda (audio)
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

פולימורפיזם הוא כמו כפתור "הפעל" אוניברסלי: במכונת כביסה הוא מכבס, במדיח הוא שוטף, אבל אתם לוחצים על אותו כפתור.

Polymorphism is like a universal "start" button: on a washing machine it washes, on a dishwasher it rinses, but you press the same button.

טעות נפוצהCommon mistake

בודקים סוג עם שרשרת if במקום לתת לכל מחלקה מתודה משלה.

Checking types with an if-chain instead of giving each class its own method.

poly.py
class Paper:
    pass

class Comic:
    pass

def describe(item):
    if isinstance(item, Paper):
        return "paper"

assert describe(Comic()) is not None, "a new kind was added and the if-chain forgot it"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/poly.py", line 11, in <module>
    assert describe(Comic()) is not None, "a new kind was added and the if-chain forgot it"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: a new kind was added and the if-chain forgot it
בעברית פשוטה: In plain words: AssertionError: a new kind was added and the if-chain forgot it: כל סוג חדש דורש לזכור לעדכן את השרשרת. עם מתודה בכל מחלקה, הסוג החדש מביא את ההתנהגות שלו איתו.AssertionError: a new kind was added and the if-chain forgot it: every new kind means remembering to update the chain. With a method in each class, the new kind brings its behaviour along.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05עץ מחלקות ו-isinstanceClass trees and isinstance

ירושה יכולה להיות כמה רמות. isinstance עונה True גם עבור כל אב בשרשרת. ובראש העץ יושבת המחלקה object, שממנה יורשת כל מחלקה בפייתון. __mro__ מראה את סדר החיפוש של פייתון.

Inheritance can go several levels. isinstance returns True for every ancestor in the chain too. At the top of the tree sits object, which every Python class inherits from. __mro__ shows Python's search order.

tree.py
class Media:
    pass

class Book(Media):
    pass

class Comic(Book):
    pass

c = Comic()
print(isinstance(c, Book), isinstance(c, Media), isinstance(c, str))
print([k.__name__ for k in Comic.__mro__])
פלטOutput
True True False
['Comic', 'Book', 'Media', 'object']
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

עץ מחלקות הוא כמו עץ משפחה: נכדה היא גם בת של ההורים וגם נכדה של הסבים.

A class tree is like a family tree: a granddaughter is both her parents' child and her grandparents' grandchild.

טעות נפוצהCommon mistake

משתמשים ב-type(x) == Book ומפספסים בנים.

Using type(x) == Book misses children.

tree.py
class Book:
    pass

class Comic(Book):
    pass

c = Comic()
assert type(c) == Book, "type() is exact: a Comic is not *exactly* a Book; use isinstance"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/tree.py", line 8, in <module>
    assert type(c) == Book, "type() is exact: a Comic is not *exactly* a Book; use isinstance"
           ^^^^^^^^^^^^^^^
AssertionError: type() is exact: a Comic is not *exactly* a Book; use isinstance
בעברית פשוטה: In plain words: AssertionError: type() is exact: ...: type משווה סוג מדויק. isinstance(c, Book) מחזיר True גם לבנים.AssertionError: type() is exact: ...: type compares the exact type. isinstance(c, Book) is True for children too.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06ירושה או הרכבה?Inheritance or composition?

כלל אצבע: אם אפשר לומר "X הוא סוג של Y" (ספר שמע הוא סוג של ספר), ירושה מתאימה. אם "ל-X יש Y" (לספרייה יש ספרים), מחזיקים אובייקט בתוך אובייקט: הרכבה. ירושה עמוקה מדי קשה לשינוי, אז כשמתלבטים, מרכיבים.

Rule of thumb: if you can say "X is a kind of Y" (an audiobook is a kind of book), inheritance fits. If "X has a Y" (a library has books), keep one object inside another: composition. Deep inheritance is hard to change, so when in doubt, compose.

compose.py
class Engine:
    def start(self):
        return "vroom"

class Car:
    def __init__(self):
        self.engine = Engine()

    def drive(self):
        return self.engine.start() + ", driving"

print(Car().drive())
פלטOutput
vroom, driving
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

לרכב יש מנוע, אבל רכב הוא לא סוג של מנוע. לכן הרכב מחזיק מנוע, ולא יורש ממנו.

A car has an engine, but a car isn't a kind of engine. So the car holds an engine instead of inheriting from it.

טעות נפוצהCommon mistake

יורשים מ-list כדי "לקבל" append, ומקבלים גם עשרות מתודות לא רצויות.

Inheriting from list to "get" append, and getting dozens of unwanted methods too.

compose.py
class Shelf(list):
    pass

s = Shelf()
s.append("Dune")
s.sort(reverse=True)
s *= 3
assert len(s) == 1, f"the shelf now has {len(s)} books: list operations leaked in"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/compose.py", line 8, in <module>
    assert len(s) == 1, f"the shelf now has {len(s)} books: list operations leaked in"
           ^^^^^^^^^^^
AssertionError: the shelf now has 3 books: list operations leaked in
בעברית פשוטה: In plain words: AssertionError: the shelf now has 3 books: ...: המדף ירש כל פעולה של רשימה, כולל כפל. עדיף self.books = [] בפנים וחשיפה רק של מה שצריך.AssertionError: the shelf now has 3 books: ...: the shelf inherited every list operation, including multiplication. Better keep self.books = [] inside and expose only what's needed.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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