חלקPart 3: קוד נקי ו-OOPClean code & OOP
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
מחלקות ואובייקטיםClasses & objects
class, __init__, self, תכונות ומתודות.
class, __init__, self, attributes and methods.
הנקודות החשובותKey points
- נתונים + פעולות במקום אחדData + actions in one place
- מילון עם פונקציות מפוזרות → מחלקהA dict with scattered functions → a class
__init__רץ ביצירה__init__runs on creationself.title = titleשומר תכונהself.title = titlestores an attributedef read(self, n):בתוך המחלקהdef read(self, n):inside the class- קוראים:
book.read(50)Call:book.read(50) - כל אובייקט שומר מצב משלוEach object keeps its own state
- שינוי אחד לא משפיע על השניChanging one doesn't affect another
- Library מחזיקה רשימת BookLibrary holds a list of Book
מונחיםTerms
- מחלקהclass: תבנית ליצירת אובייקטים: מגדירה אילו נתונים יש לכל אחד ומה הוא יודע לעשות. כותבים
class Book:.A blueprint for making objects: defines what data each has and what it can do. Writtenclass Book:. - אובייקטobject: מופע אחד שנוצר ממחלקה, עם ערכים משלו.
Book("Dune")יוצר אובייקט.One instance made from a class, with its own values.Book("Dune")makes an object. - תכונהattribute: משתנה ששייך לאובייקט, נגיש עם נקודה:
book.title.A variable that belongs to an object, reached with a dot:book.title. - selfself: הפרמטר הראשון של כל מתודה: האובייקט שעליו קראו לה. פייתון מעבירה אותו לבד.The first parameter of every method: the object it was called on. Python passes it for you.
- בנאי (__init__)constructor (__init__): המתודה
__init__שרצה אוטומטית כשיוצרים אובייקט חדש וממלאת את התכונות שלו.The__init__method that runs automatically when a new object is made and fills in its attributes. - מופעinstance: מילה נרדפת לאובייקט: "מופע של המחלקה Book".Another word for object: "an instance of the Book class".
Cheatsheet
למהWhy
book = {"title": "Dune", "pages": 412, "read": 0}
def read_pages(b, n):
b["read"] += n
read_pages(book, 50)
print(book)מתודותMethods
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
self.read = 0
def read_pages(self, n):הרכבהComposition
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
class Library:
def __init__(self):תכנוןDesign
class ReadingGoal:
"""A yearly goal: read N books."""
def __init__(self, year, target):
self.year = year
self.target = target
self.done = []שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
TypeError | שוכחים את הסוגריים ומקבלים את המחלקה עצמה במקום אובייקט.Forgetting the parentheses gives you the class itself, not an object. | TypeError: Book.read_pages() missing 1 required positional argument: 'n': בלי () b היא המחלקה עצמה, ולכן 10 נכנס ל-self ול-n לא נשאר ערך. כותבים b = Book().TypeError: Book.read_pages() missing 1 required positional argument: 'n': without () b is the class itself, so 10 went into self and n got nothing. Write b = Book(). |
AttributeError | שוכחים את self. ושומרים במשתנה מקומי שנעלם.Forgetting self. stores into a local variable that vanishes. | AttributeError: 'Book' object has no attribute 'title': בלי self. זה סתם משתנה מקומי בתוך __init__. כותבים self.title = title.AttributeError: 'Book' object has no attribute 'title': without self. it's just a local variable inside __init__. Write self.title = title. |
TypeError | שוכחים את self ברשימת הפרמטרים של המתודה.Forgetting self in the method's parameter list. | TypeError: Book.shout() takes 0 positional arguments but 1 was given: פייתון העבירה את האובייקט, ולא היה מקום לקבל אותו. מוסיפים self.TypeError: Book.shout() takes 0 positional arguments but 1 was given: Python passed the object and there was no slot for it. Add self. |
AssertionError | חושבים ש-= מעתיק אובייקט.Thinking = copies an object. | AssertionError: backup changed too: ['pen']: backup הוא אותו אובייקט. לעותק אמיתי יוצרים אובייקט חדש (או copy.deepcopy).AssertionError: backup changed too: ['pen']: backup is the same object. For a real copy, make a new object (or copy.deepcopy). |
AttributeError | משתמשים בתוצאה של find בלי לבדוק None.Using find's result without checking for None. | AttributeError: 'NoneType' object has no attribute 'pages': לא נמצא ספר, וקיבלנו None. בודקים if book is not None: לפני השימוש.AttributeError: 'NoneType' object has no attribute 'pages': no book was found and we got None. Check if book is not None: before using it. |
TypeError | קוראים למתודה בלי סוגריים ומקבלים את המתודה עצמה.Calling a method without parentheses gives you the method itself. | TypeError: unsupported operand type(s) for +: 'method' and 'int': g.left הוא המתודה, g.left() הוא התוצאה.TypeError: unsupported operand type(s) for +: 'method' and 'int': g.left is the method, g.left() is the result. |