חלקPart 3: קוד נקי ו-OOPClean code & OOP
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Dunder methodsDunder methods
__str__, __repr__, __eq__, __lt__, __len__ ומה הם נותנים.
__str__, __repr__, __eq__, __lt__, __len__ and what they give you.
הנקודות החשובותKey points
- שני קווים תחתונים מכל צדTwo underscores on each side
- פייתון קוראת להן בעצמהPython calls them itself
- __str__: למשתמש, print__str__: for users, print
- __repr__: למתכנת, רשימות ודיבאג__repr__: for programmers, lists and debugging
- ברירת מחדל:
==משווה זהותDefault:==compares identity __eq__קובע מה נחשב שווה__eq__decides what counts as equal__lt__= less than,<__lt__= less than,<- מספיק כדי ש-
sortedיעבודEnough forsortedto work __len__→len(shelf)__len__→len(shelf)
מונחיםTerms
- מתודת dunderdunder method: מתודה ששמה מוקף בשני קווים תחתונים (double underscore), כמו
__str__. פייתון קוראת לה אוטומטית בפעולות מוכרות כמו print, ==, len.A method whose name is wrapped in double underscores, like__str__. Python calls it automatically for familiar operations like print, ==, len. - __repr____repr__: ייצוג טכני של אובייקט, למתכנתים: מה שרואים ברשימה או בדיבאגר. רצוי שייראה כמו הקוד שיוצר את האובייקט.An object's technical representation, for programmers: what you see in a list or the debugger. Ideally looks like the code that creates it.
- __str____str__: ייצוג ידידותי של אובייקט, למשתמשים: מה ש-print ו-str() מציגים.An object's friendly representation, for users: what print and str() show.
- העמסת אופרטוריםoperator overloading: הגדרה מה עושים אופרטורים כמו
+,==,<עם אובייקטים שלכם, בעזרת מתודות dunder.Defining what operators like+,==,<do with your objects, using dunder methods. - אוסף שאפשר לעבור עליוiterable: אובייקט שאפשר לשים בלולאת for. מחלקה נעשית כזו כשיש לה
__iter__.An object you can put in a for loop. A class becomes one when it has__iter__.
Cheatsheet
dunderdunder
class Book:
def __init__(self, title):
self.title = title
b = Book("Dune")
print(b)
print("Dune".__len__(), len("Dune"))הדפסהPrinting
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"שוויוןEquality
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __eq__(self, other):
if not isinstance(other, Book):מיוןSorting
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __lt__(self, other):
return self.pages < other.pagesאוסףCollection
class Shelf:
def __init__(self, *titles):
self.books = list(titles)
def __len__(self):
return len(self.books)
אופרטוריםOperators
class Duration:
def __init__(self, minutes):
self.minutes = minutes
def __add__(self, other):
return Duration(self.minutes + other.minutes)
שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
TypeError | קוראים לאובייקט כמו לרשימה בלי __len__.Using len on an object that 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. |
TypeError | מחזירים מ-__str__ משהו שאינו מחרוזת.Returning a non-string from __str__. | 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". |
AssertionError | שוכחים את __eq__ ומתפלאים שהספר לא נמצא ברשימה.Forgetting __eq__ and wondering why the book isn't found in a list. | AssertionError: not found: ...: in משתמש ב-==, ובלי __eq__ זה בודק זהות. מוסיפים __eq__.AssertionError: not found: ...: in uses ==, and without __eq__ that's identity. Add __eq__. |
TypeError | ממיינים אובייקטים בלי __lt__ ובלי key.Sorting objects with neither __lt__ nor key. | 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=. |
TypeError | מחזירים את הרשימה עצמה מ-__iter__ במקום איטרטור.Returning the list itself from __iter__ instead of an iterator. | 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). |
TypeError | sum על אובייקטים בלי ערך התחלתי מתאים.sum over objects without a matching start value. | 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)). |