נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • class EBook(Book):class EBook(Book):
  • הבן מקבל הכול מהאבThe child gets everything from the parent
  • הבן מוסיף תכונה משלוThe child adds its own attribute
  • super().__init__(...) מפעיל את האבsuper().__init__(...) runs the parent's
  • אותו שם מתודה בבן = גרסה חדשהSame method name in the child = a new version
  • super().label() משתמש בגרסה של האבsuper().label() reuses the parent's version
  • רשימה של סוגים שוניםA list of different kinds
  • אותה קריאה לכולםThe same call for all
  • אפשר לרשת מבן של בןYou can inherit from a child of a child

מונחיםTerms

  • ירושהinheritance: מחלקה חדשה שמקבלת את כל התכונות והמתודות של מחלקה קיימת ומוסיפה או משנה. class EBook(Book):.A new class that gets all attributes and methods of an existing one and adds or changes some. class EBook(Book):.
  • מחלקת אבparent class: המחלקה שממנה יורשים (נקראת גם base class או superclass).The class being inherited from (also called base class or superclass).
  • מחלקת בןchild class: המחלקה שיורשת (נקראת גם subclass).The class that inherits (also called a subclass).
  • דריסה (override)override: כתיבה מחדש של מתודה שכבר קיימת אצל האב, כדי שהבן יתנהג אחרת.Rewriting a method the parent already has, so the child behaves differently.
  • super()super(): גישה למתודות של מחלקת האב מתוך מחלקת הבן, למשל super().__init__(title).Access to the parent class's methods from inside the child, e.g. super().__init__(title).
  • פולימורפיזםpolymorphism: אותה קריאה (item.describe()) עובדת על אובייקטים מסוגים שונים, וכל אחד מגיב בדרך שלו.The same call (item.describe()) works on different kinds of objects, each responding in its own way.
  • isinstanceisinstance: בדיקה אם אובייקט שייך למחלקה (או לבן שלה): isinstance(b, Book).Checks whether an object belongs to a class (or a child of it): isinstance(b, Book).

Cheatsheet

ירושהInheritance
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def label(self):
        return f"{self.title} by {self.author}"
דריסהOverride
class Book:
    def __init__(self, title):
        self.title = title

    def label(self):
        return f"Book: {self.title}"
פולימורפיזםPolymorphism
class Item:
    def __init__(self, title):
        self.title = title

    def describe(self):
        return f"{self.title}"
עץTree
class Media:
    pass

class Book(Media):
    pass

class Comic(Book):
מתיWhen
class Engine:
    def start(self):
        return "vroom"

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

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AttributeErrorקוראים למתודה של הבן על אובייקט של האב.Calling a child's method on a parent object.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.
AttributeErrorשוכחים לקרוא ל-super().__init__.Forgetting to call super().__init__.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).
AssertionErrorשגיאת כתיב בשם המתודה, ולכן הדריסה לא קורית בכלל.A typo in the method name, so the override never happens.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.
AssertionErrorבודקים סוג עם שרשרת if במקום לתת לכל מחלקה מתודה משלה.Checking types with an if-chain instead of giving each class its own method.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.
AssertionErrorמשתמשים ב-type(x) == Book ומפספסים בנים.Using type(x) == Book misses children.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.
AssertionErrorיורשים מ-list כדי "לקבל" append, ומקבלים גם עשרות מתודות לא רצויות.Inheriting from list to "get" append, and getting dozens of unwanted methods too.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.

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