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

PythonPython
15
חלקPart 3: קוד נקי ו-OOPClean code & OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

מחלקות ואובייקטיםClasses & objects

class, __init__, self, תכונות ומתודות.

class, __init__, self, attributes and methods.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • נתונים + פעולות במקום אחדData + actions in one place
  • מילון עם פונקציות מפוזרות → מחלקהA dict with scattered functions → a class
  • __init__ רץ ביצירה__init__ runs on creation
  • self.title = title שומר תכונהself.title = title stores an attribute
  • def 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. Written class 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.

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