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

חזרה למפגשBack
PythonPython

Dunder methodsDunder methods

מפגש 17: __str__, __repr__, __eq__, __lt__, __len__ ומה הם נותנים.Session 17: __str__, __repr__, __eq__, __lt__, __len__ and what they give you.

מה נעשה היוםToday's plan

  • dunderdunder
  • הדפסהPrinting
  • שוויוןEquality
  • מיוןSorting
  • אוסףCollection
  • אופרטוריםOperators
נושאTopic 1

dunderdunder

מה זה dunder?What is dunder?

  • שני קווים תחתונים מכל צדTwo underscores on each side
  • פייתון קוראת להן בעצמהPython calls them itself
  • len(x) → x.__len__()len(x) → x.__len__()
שאלה לכיתהQuestion for the class

מה ידפיס הקוד?What will this print?

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

b = Book("Dune")
print(b)
print("Dune".__len__(), len("Dune"))
print((3).__add__(4), 3 + 4)

    dunderdunder

    dunder.py
    class Book:
        def __init__(self, title):
            self.title = title
    
    b = Book("Dune")
    print(b)
    print("Dune".__len__(), len("Dune"))
    print((3).__add__(4), 3 + 4)
    פלטOutput
    <__main__.Book object at 0x7fac61496cf0>
    4 4
    7 7

    אנלוגיהAnalogy

    מתודות dunder הן כמו שקעים סטנדרטיים בקיר: אם המכשיר שלכם מתאים לשקע, הוא פשוט עובד עם החשמל של הבית.Dunder methods are like standard wall sockets: if your device fits the socket, it just works with the house's power.

    טעות נפוצהCommon mistake

    dunder.py
    class Shelf:
        def __init__(self):
            self.books = ["Dune", "Emma"]
    
    print(len(Shelf()))
    מה Python עונהWhat Python says
    TypeError: object of type 'Shelf' has no len()
    TypeError: object of type 'Shelf' has no len(): פייתון חיפשה __len__ ולא מצאה. נוסיף אותה בהמשך.TypeError: object of type 'Shelf' has no len(): Python looked for __len__ and found none. We'll add it later on.
    נושאTopic 2

    הדפסהPrinting

    __str__ ו-__repr____str__ and __repr__

    • __str__: למשתמש, print__str__: for users, print
    • __repr__: למתכנת, רשימות ודיבאג__repr__: for programmers, lists and debugging
    • !r ב-f-string קורא ל-repr!r in an f-string calls repr

    אנלוגיהAnalogy

    __str__ הוא כרטיס הביקור שאתם נותנים ללקוחות, __repr__ הוא התיק הרפואי שהרופא קורא: אותו אדם, פרטים שונים לקהל שונה.__str__ is the business card you give clients, __repr__ is the medical file a doctor reads: same person, different details for a different audience.
    נושאTopic 3

    שוויוןEquality

    השוואה: __eq__Comparing: __eq__

    • ברירת מחדל: == משווה זהותDefault: == compares identity
    • __eq__ קובע מה נחשב שווה__eq__ decides what counts as equal
    • מחזירים NotImplemented לסוג זרReturn NotImplemented for a foreign type

    אנלוגיהAnalogy

    is שואל "זה אותו אדם?", == שואל "יש להם אותם פרטים?". תאומים זהים הם == אבל לא is.is asks "is it the same person?", == asks "do they have the same details?". Identical twins are == but not is.
    נושאTopic 4

    מיוןSorting

    מיון: __lt__Sorting: __lt__

    • __lt__ = less than, <__lt__ = less than, <
    • מספיק כדי ש-sorted יעבודEnough for sorted to work
    • או: sorted(..., key=...) בלי dunderOr: sorted(..., key=...) without dunder

    אנלוגיהAnalogy

    __lt__ הוא כמו לתת לשופט חוק אחד: "מי מהשניים קטן יותר". מזה הוא כבר יודע לסדר את כל התחרות.__lt__ is like giving a referee one rule: "which of two is smaller". From that alone they can rank the whole contest.

    טעות נפוצהCommon mistake

    sort.py
    class Book:
        def __init__(self, pages):
            self.pages = pages
    
    print(sorted([Book(412), Book(240)]))
    מה Python עונהWhat Python says
    TypeError: '<' not supported between instances of 'Book' and 'Book'
    TypeError: '<' not supported between instances of 'Book' and 'Book': פייתון לא יודעת איך להשוות ספרים. מוסיפים __lt__ או key=.TypeError: '<' not supported between instances of 'Book' and 'Book': Python doesn't know how to compare books. Add __lt__ or key=.
    נושאTopic 5

    אוסףCollection

    אוסף משלכםYour own collection

    • __len__ → len(shelf)__len__ → len(shelf)
    • __contains__ → "Dune" in shelf__contains__ → "Dune" in shelf
    • __iter__ → for b in shelf__iter__ → for b in shelf

    אנלוגיהAnalogy

    שלוש המתודות הן כמו שלט, פעמון ודלת לבית: אפשר לדעת כמה גרים בו, לבדוק אם מישהו בבית, ולהיכנס לסיבוב.The three methods are like a sign, a doorbell and a door: you can tell how many live there, check if someone's home, and walk through.
    נושאTopic 6

    אופרטוריםOperators

    אופרטורים: __add__Operators: __add__

    • a + b → a.__add__(b)a + b → a.__add__(b)
    • מחזירים אובייקט חדשReturn a new object
    • רק כשהמשמעות ברורהOnly when the meaning is obvious

    אנלוגיהAnalogy

    העמסת + היא כמו להחליט שחיבור של שני מתכונים פירושו ארוחה: הגיוני, כל עוד כולם מבינים את זה באותה צורה.Overloading + is like deciding that adding two recipes means a meal: makes sense, as long as everyone reads it the same way.

    שני קווים תחתונים מכל צדTwo underscores on each side

    פייתון קוראת להן בעצמהPython calls them itself

    len(x) → x.__len__()len(x) → x.__len__()

    __str__: למשתמש, print__str__: for users, print

    __repr__: למתכנת, רשימות ודיבאג__repr__: for programmers, lists and debugging

    !r ב-f-string קורא ל-repr!r in an f-string calls repr

    ברירת מחדל: == משווה זהותDefault: == compares identity

    __eq__ קובע מה נחשב שווה__eq__ decides what counts as equal

    מחזירים NotImplemented לסוג זרReturn NotImplemented for a foreign type

    __lt__ = less than, <__lt__ = less than, <

    מספיק כדי ש-sorted יעבודEnough for sorted to work

    או: sorted(..., key=...) בלי dunderOr: sorted(..., key=...) without dunder

    __len__ → len(shelf)__len__ → len(shelf)

    __contains__ → "Dune" in shelf__contains__ → "Dune" in shelf

    מה למדנוWhat we learned

    • שני קווים תחתונים מכל צדTwo underscores on each side
    • __str__: למשתמש, print__str__: for users, print
    • ברירת מחדל: == משווה זהותDefault: == compares identity
    • __lt__ = less than, <__lt__ = less than, <
    • __len__ → len(shelf)__len__ → len(shelf)
    • a + b → a.__add__(b)a + b → a.__add__(b)

    עכשיו לתרגולNow, practice

    5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
    הערות מרצהSpeaker notes

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