Dunder methodsDunder methods
__str__, __repr__, __eq__, __lt__, __len__ ומה הם נותנים.
__str__, __repr__, __eq__, __lt__, __len__ and what they give you.
01מה זה dunder?What is dunder?
כבר פגשתם אחת: __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)<__main__.Book object at 0x7fac61496cf0> 4 4 7 7
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מתודות dunder הן כמו שקעים סטנדרטיים בקיר: אם המכשיר שלכם מתאים לשקע, הוא פשוט עובד עם החשמל של הבית.
Dunder methods are like standard wall sockets: if your device fits the socket, it just works with the house's power.
קוראים לאובייקט כמו לרשימה בלי __len__.
Using len on an object that has no __len__.
class Shelf:
def __init__(self):
self.books = ["Dune", "Emma"]
print(len(Shelf()))Traceback (most recent call last):
File "/Users/you/python-course/dunder.py", line 5, in <module>
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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02__str__ ו-__repr____str__ and __repr__
בלי הגדרה, print מציג משהו כמו <__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.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
def __repr__(self):
return f"Book({self.title!r}, {self.author!r})"
b = Book("Dune", "Frank Herbert")
print(b)
print([b])
print(f"{b!r}")Dune by Frank Herbert
[Book('Dune', 'Frank Herbert')]
Book('Dune', 'Frank Herbert')__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.
מחזירים מ-__str__ משהו שאינו מחרוזת.
Returning a non-string from __str__.
class Book:
def __init__(self, pages):
self.pages = pages
def __str__(self):
return self.pages
print(Book(412))Traceback (most recent call last):
File "/Users/you/python-course/str_repr.py", line 8, in <module>
print(Book(412))
~~~~~^^^^^^^^^^^
TypeError: __str__ returned non-string (type int)TypeError: __str__ returned non-string (type int): __str__ חייבת להחזיר str. עוטפים ב-f-string: return f"{self.pages} pages".TypeError: __str__ returned non-string (type int): __str__ must return a str. Wrap it: return f"{self.pages} pages".צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
__str__ קובע מה print יראה.
__str__ decides what print shows.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
print(Point(3, 4))(3, 4)
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03השוואה: __eq__Comparing: __eq__
בלי __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.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __eq__(self, other):
if not isinstance(other, Book):
return NotImplemented
return (self.title, self.author) == (other.title, other.author)
a = Book("Dune", "Frank Herbert")
b = Book("Dune", "Frank Herbert")
print(a == b, a is b, a == "Dune")
print(b in [a])True False False True
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
is שואל "זה אותו אדם?", == שואל "יש להם אותם פרטים?". תאומים זהים הם == אבל לא is.
is asks "is it the same person?", == asks "do they have the same details?". Identical twins are == but not is.
שוכחים את __eq__ ומתפלאים שהספר לא נמצא ברשימה.
Forgetting __eq__ and wondering why the book isn't found in a list.
class Book:
def __init__(self, title):
self.title = title
shelf = [Book("Dune")]
assert Book("Dune") in shelf, "not found: without __eq__, `in` compares identity"Traceback (most recent call last):
File "/Users/you/python-course/eq.py", line 6, in <module>
assert Book("Dune") in shelf, "not found: without __eq__, `in` compares identity"
^^^^^^^^^^^^^^^^^^^^^
AssertionError: not found: without __eq__, `in` compares identityAssertionError: not found: ...: in משתמש ב-==, ובלי __eq__ זה בודק זהות. מוסיפים __eq__.AssertionError: not found: ...: in uses ==, and without __eq__ that's identity. Add __eq__.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04מיון: __lt__Sorting: __lt__
sorted משווה זוגות עם <. אם מגדירים __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.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __lt__(self, other):
return self.pages < other.pages
def __repr__(self):
return f"{self.title}({self.pages})"
shelf = [Book("Emma", 474), Book("Matilda", 240), Book("Dune", 412)]
print(sorted(shelf))
print(max(shelf))
print(sorted(shelf, key=lambda b: b.title))[Matilda(240), Dune(412), Emma(474)] Emma(474) [Dune(412), Emma(474), Matilda(240)]
__lt__ הוא כמו לתת לשופט חוק אחד: "מי מהשניים קטן יותר". מזה הוא כבר יודע לסדר את כל התחרות.
__lt__ is like giving a referee one rule: "which of two is smaller". From that alone they can rank the whole contest.
ממיינים אובייקטים בלי __lt__ ובלי key.
Sorting objects with neither __lt__ nor key.
class Book:
def __init__(self, pages):
self.pages = pages
print(sorted([Book(412), Book(240)]))Traceback (most recent call last):
File "/Users/you/python-course/sort.py", line 5, in <module>
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=.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05אוסף משלכםYour own collection
שלוש מתודות הופכות מחלקה לאוסף אמיתי. __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.
class Shelf:
def __init__(self, *titles):
self.books = list(titles)
def __len__(self):
return len(self.books)
def __contains__(self, title):
return title.lower() in (b.lower() for b in self.books)
def __iter__(self):
return iter(self.books)
shelf = Shelf("Dune", "Emma", "Matilda")
print(len(shelf), "dune" in shelf, "Ulysses" in shelf)
for t in shelf:
print("-", t)
print(sorted(shelf))3 True False - Dune - Emma - Matilda ['Dune', 'Emma', 'Matilda']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
שלוש המתודות הן כמו שלט, פעמון ודלת לבית: אפשר לדעת כמה גרים בו, לבדוק אם מישהו בבית, ולהיכנס לסיבוב.
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.
מחזירים את הרשימה עצמה מ-__iter__ במקום איטרטור.
Returning the list itself from __iter__ instead of an iterator.
class Shelf:
def __init__(self):
self.books = ["Dune"]
def __iter__(self):
return self.books
for b in Shelf():
print(b)Traceback (most recent call last):
File "/Users/you/python-course/shelf.py", line 8, in <module>
for b in Shelf():
~~~~~^^
TypeError: iter() returned non-iterator of type 'list'TypeError: iter() returned non-iterator of type 'list': __iter__ חייבת להחזיר איטרטור. עוטפים: return iter(self.books).TypeError: iter() returned non-iterator of type 'list': __iter__ must return an iterator. Wrap it: return iter(self.books).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06אופרטורים: __add__Operators: __add__
העמסת אופרטורים: אפשר להגדיר מה עושה + בין שני אובייקטים. למשל זמן קריאה: 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.
class Duration:
def __init__(self, minutes):
self.minutes = minutes
def __add__(self, other):
return Duration(self.minutes + other.minutes)
def __str__(self):
h, m = divmod(self.minutes, 60)
return f"{h}:{m:02d}"
monday = Duration(100)
tuesday = Duration(35)
print(monday + tuesday)
print(sum([monday, tuesday], Duration(0)))2:15 2:15
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
העמסת + היא כמו להחליט שחיבור של שני מתכונים פירושו ארוחה: הגיוני, כל עוד כולם מבינים את זה באותה צורה.
Overloading + is like deciding that adding two recipes means a meal: makes sense, as long as everyone reads it the same way.
sum על אובייקטים בלי ערך התחלתי מתאים.
sum over objects without a matching start value.
class Duration:
def __init__(self, minutes):
self.minutes = minutes
def __add__(self, other):
return Duration(self.minutes + other.minutes)
print(sum([Duration(10), Duration(20)]))Traceback (most recent call last):
File "/Users/you/python-course/duration.py", line 8, in <module>
print(sum([Duration(10), Duration(20)]))
~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'Duration'TypeError: unsupported operand type(s) for +: 'int' and 'Duration': sum מתחיל מ-0 (int). נותנים התחלה: sum(items, Duration(0)).TypeError: unsupported operand type(s) for +: 'int' and 'Duration': sum starts from 0 (an int). Give a start: sum(items, Duration(0)).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
__add__ מאפשר להשתמש ב-+ על עצמים שלנו.
__add__ lets us use + on our own objects.
class Coins:
def __init__(self, n):
self.n = n
def __add__(self, other):
return Coins(self.n + other.n)
total = Coins(5) + Coins(7)
print(total.n)12
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.