נבנה על ידיBuilt by Ariel Yohimovich
len(x) → x.__len__()len(x) → x.__len__()__init__. מתודות dunder הן "ווים" שפייתון מפעילה מאחורי הקלעים. print(x) קורא ל-x.__str__(), a == b קורא ל-a.__eq__(b), ו-len(x) קורא ל-x.__len__(). כשכותבים אותן במחלקה, האובייקטים שלכם מתנהגים כמו טיפוסים מובנים.You've met one already: __init__. Dunder methods are hooks Python triggers behind the scenes. print(x) calls x.__str__(), a == b calls a.__eq__(b), and len(x) calls x.__len__(). Write them in a class and your objects behave like built-in types.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)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)<__main__.Book object at 0x7fac61496cf0> 4 4 7 7
class Shelf:
def __init__(self):
self.books = ["Dune", "Emma"]
print(len(Shelf()))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.__len__.Using len on an object that has no __len__.!r ב-f-string קורא ל-repr!r in an f-string calls repr<__main__.Book object at 0x7f...>, מידע שלא עוזר לאף אחד. __str__ קובע מה רואה המשתמש, ו-__repr__ קובע מה רואה המתכנת: מה שמופיע כשמדפיסים רשימה של ספרים, ובדיבאגר.Without them, print shows something like <__main__.Book object at 0x7f...>, which helps nobody. __str__ decides what the user sees, and __repr__ what the programmer sees: what appears when printing a list of books, and in the debugger.__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.== משווה זהותDefault: == compares identity__eq__ קובע מה נחשב שווה__eq__ decides what counts as equalNotImplemented לסוג זרReturn NotImplemented for a foreign type__eq__, שני ספרים עם אותה כותרת אינם שווים: == בודק אם זה אותו אובייקט בזיכרון. עם __eq__ אנחנו מחליטים: למשל, ספרים שווים אם הכותרת והסופר זהים. אם משווים לסוג אחר, מחזירים NotImplemented ופייתון תטפל בזה.Without __eq__, two books with the same title aren't equal: == checks whether it's the same object in memory. With __eq__ we decide: say, books are equal if title and author match. When compared to another type, return NotImplemented and Python handles it.is שואל "זה אותו אדם?", == שואל "יש להם אותם פרטים?". תאומים זהים הם == אבל לא is.is asks "is it the same person?", == asks "do they have the same details?". Identical twins are == but not is.__lt__ = less than, <__lt__ = less than, <sorted יעבודEnough for sorted to worksorted(..., key=...) בלי dunderOr: sorted(..., key=...) without dundersorted משווה זוגות עם <. אם מגדירים __lt__, ספרים יודעים למיין את עצמם. אפשרות שנייה, לפעמים פשוטה יותר: key=lambda b: b.pages, שמתאימה כשרוצים כמה סדרים שונים.sorted compares pairs with <. Define __lt__ and books know how to sort themselves. A second option, sometimes simpler: key=lambda b: b.pages, handy when you want several different orders.__lt__ הוא כמו לתת לשופט חוק אחד: "מי מהשניים קטן יותר". מזה הוא כבר יודע לסדר את כל התחרות.__lt__ is like giving a referee one rule: "which of two is smaller". From that alone they can rank the whole contest.class Book:
def __init__(self, pages):
self.pages = pages
print(sorted([Book(412), Book(240)]))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=.__lt__ ובלי key.Sorting objects with neither __lt__ nor key.__len__ → len(shelf)__len__ → len(shelf)__contains__ → "Dune" in shelf__contains__ → "Dune" in shelf__iter__ → for b in shelf__iter__ → for b in shelf__len__ מחזירה מספר, __contains__ מחזירה True או False, ו-__iter__ מחזירה משהו שאפשר לעבור עליו (הכי פשוט: iter(self.books)). מעכשיו המדף הוא אוסף שאפשר לעבור עליו.Three methods turn a class into a real collection. __len__ returns a number, __contains__ returns True or False, and __iter__ returns something to loop over (simplest: iter(self.books)). From now on the shelf is an iterable.a + b → a.__add__(b)a + b → a.__add__(b)+ בין שני אובייקטים. למשל זמן קריאה: 1:40 ועוד 0:35 הם 2:15. כלל חשוב: עושים את זה רק כשהמשמעות ברורה לכל קורא, ומחזירים אובייקט חדש בלי לשנות את הקיימים.Operator overloading: you can define what + does between two objects. For example reading time: 1:40 plus 0:35 is 2:15. Key rule: do it only when the meaning is obvious to any reader, and return a new object without changing the existing ones.+ היא כמו להחליט שחיבור של שני מתכונים פירושו ארוחה: הגיוני, כל עוד כולם מבינים את זה באותה צורה.Overloading + is like deciding that adding two recipes means a meal: makes sense, as long as everyone reads it the same way.len(x) → x.__len__()len(x) → x.__len__()!r ב-f-string קורא ל-repr!r in an f-string calls repr== משווה זהותDefault: == compares identity__eq__ קובע מה נחשב שווה__eq__ decides what counts as equalNotImplemented לסוג זרReturn NotImplemented for a foreign type__lt__ = less than, <__lt__ = less than, <sorted יעבודEnough for sorted to worksorted(..., key=...) בלי dunderOr: sorted(..., key=...) without dunder__len__ → len(shelf)__len__ → len(shelf)__contains__ → "Dune" in shelf__contains__ → "Dune" in shelf== משווה זהות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)נבנה על ידיBuilt by Ariel Yohimovich