מחלקות ואובייקטיםClasses & objects
class, __init__, self, תכונות ומתודות.
class, __init__, self, attributes and methods.
01למה מחלקות?Why classes?
עד עכשיו ספר היה מילון, והפונקציות שעובדות עליו ישבו בנפרד. מחלקה מאחדת את שניהם: היא מגדירה אילו נתונים יש לכל ספר ומה ספר יודע לעשות. מכל מחלקה יוצרים כמה אובייקטים שרוצים.
Until now a book was a dict, and the functions working on it lived elsewhere. A class joins both: it defines what data every book has and what a book can do. From one class you make as many objects as you like.
book = {"title": "Dune", "pages": 412, "read": 0}
def read_pages(b, n):
b["read"] += n
read_pages(book, 50)
print(book){'title': 'Dune', 'pages': 412, 'read': 50}צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מחלקה היא כמו תבנית עוגיות: התבנית אחת, ומכל לחיצה יוצאת עוגייה חדשה. כל עוגייה יכולה לקבל קישוט אחר, אבל הצורה זהה.
A class is like a cookie cutter: one cutter, and every press makes a new cookie. Each can be decorated differently, but the shape is the same.
שוכחים את הסוגריים ומקבלים את המחלקה עצמה במקום אובייקט.
Forgetting the parentheses gives you the class itself, not an object.
class Book:
def __init__(self):
self.read = 0
def read_pages(self, n):
self.read += n
b = Book
b.read_pages(10)Traceback (most recent call last):
File "/Users/you/python-course/why.py", line 9, in <module>
b.read_pages(10)
~~~~~~~~~~~~^^^^
TypeError: Book.read_pages() missing 1 required positional argument: 'n'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().צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02__init__ ו-self__init__ and self
הבנאי __init__ רץ אוטומטית כשכותבים Book(...). הפרמטר הראשון, self, הוא האובייקט החדש, וכל self.x = ... יוצר לו תכונה. את self לא מעבירים בעצמנו: פייתון עושה את זה.
The constructor (__init__) __init__ runs automatically when you write Book(...). Its first parameter, self, is the new object, and every self.x = ... gives it an attribute. You don't pass self yourself: Python does.
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
self הוא כמו המילה "שלי": כשכל ספר אומר "הכותרת שלי", כל אחד מתכוון לכותרת שלו.
self is like the word "my": when each book says "my title", each means its own.
שוכחים את self. ושומרים במשתנה מקומי שנעלם.
Forgetting self. stores into a local variable that vanishes.
class Book:
def __init__(self, title):
title = title
b = Book("Dune")
print(b.title)Traceback (most recent call last):
File "/Users/you/python-course/book.py", line 6, in <module>
print(b.title)
^^^^^^^
AttributeError: 'Book' object has no attribute 'title'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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
__init__ ממלא את העצם החדש בפרטים שלו.
__init__ fills the new object with its details.
class Pet:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}"
print(Pet("Rex", "woof").speak())
print(Pet("Mitzi", "meow").speak())Rex says woof Mitzi says meow
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03מתודותMethods
מתודה היא פונקציה בתוך מחלקה. כשכותבים a.read(50), פייתון קוראת ל-Book.read(a, 50), כלומר a נכנס ל-self. מתודה יכולה לשנות תכונות, להחזיר חישוב, או שניהם.
A method is a function inside a class. When you write a.read(50), Python calls Book.read(a, 50), so a goes into self. A method can change attributes, return a calculation, or both.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
self.read = 0
def read_pages(self, n):
self.read = min(self.read + n, self.pages)
def progress(self):
return round(self.read / self.pages * 100)
def is_done(self):
return self.read == self.pages
b = Book("Dune", 412)
b.read_pages(103)
print(b.progress(), "%")
b.read_pages(1000)
print(b.progress(), "%", b.is_done())25 % 100 % True
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מתודות הן כמו הכפתורים של מכשיר: לכל מכשיר כפתורים משלו, והם פועלים רק עליו.
Methods are like a device's buttons: each device has its own, and they act only on it.
שוכחים את self ברשימת הפרמטרים של המתודה.
Forgetting self in the method's parameter list.
class Book:
def __init__(self, title):
self.title = title
def shout():
return "READ ME"
print(Book("Dune").shout())Traceback (most recent call last):
File "/Users/you/python-course/book.py", line 8, in <module>
print(Book("Dune").shout())
~~~~~~~~~~~~~~~~~~^^
TypeError: Book.shout() takes 0 positional arguments but 1 was givenTypeError: 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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04אובייקטים זוכריםObjects remember
כמו רשימות, אובייקטים הם ניתנים לשינוי. c = a לא יוצר עותק: זה עוד שם לאותו אובייקט. בסימולציה רואים את החצים: שני שמות, ספר אחד.
Like lists, objects are mutable. c = a makes no copy: it's another name for the same object. In the simulation you can see the arrows: two names, one book.
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
שני שמות לאובייקט אחד הם כמו כינוי: "דני" ו"דניאל" הם אותו אדם. אם דני מסתפר, גם דניאל מסתפר.
Two names for one object are like a nickname: "Danny" and "Daniel" are the same person. If Danny gets a haircut, so does Daniel.
חושבים ש-= מעתיק אובייקט.
Thinking = copies an object.
class Box:
def __init__(self):
self.items = []
mine = Box()
backup = mine
mine.items.append("pen")
assert backup.items == [], f"backup changed too: {backup.items}"Traceback (most recent call last):
File "/Users/you/python-course/box.py", line 8, in <module>
assert backup.items == [], f"backup changed too: {backup.items}"
^^^^^^^^^^^^^^^^^^
AssertionError: backup changed too: ['pen']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).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
עצם זוכר מצב: כאן מספר הצעדים גדל.
An object remembers state: here the step count grows.
class Counter:
def __init__(self):
self.steps = 0
def walk(self, n):
self.steps += n
c = Counter()
c.walk(100)
c.walk(250)
print(c.steps)350
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05מחלקה שמחזיקה מחלקותA class that holds classes
תוכניות אמיתיות בנויות מכמה מחלקות שעובדות יחד. Library מחזיקה רשימה של Book, ויודעת להוסיף, לחפש ולסכם. כל מחלקה דואגת לעניין שלה: הספר יודע על עצמו, הספרייה יודעת על האוסף.
Real programs are built from several classes working together. Library holds a list of Book and can add, search and summarise. Each class minds its own business: a book knows about itself, the library about the collection.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
class Library:
def __init__(self):
self.books = []
def add(self, book):
self.books.append(book)
def total_pages(self):
return sum(b.pages for b in self.books)
def find(self, title):
for b in self.books:
if b.title.lower() == title.lower():
return b
return None
lib = Library()
lib.add(Book("Dune", 412))
lib.add(Book("Emma", 474))
print(len(lib.books), lib.total_pages())
print(lib.find("emma").pages, lib.find("Ulysses"))2 886 474 None
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
ספרייה ומדפים הם כמו תזמורת ונגנים: כל נגן יודע לנגן בכלי שלו, והמנצח רק מתאם ביניהם.
A library and its books are like an orchestra and players: each player plays their instrument, the conductor just coordinates.
משתמשים בתוצאה של find בלי לבדוק None.
Using find's result without checking for None.
class Library:
def __init__(self):
self.books = []
def find(self, title):
return None
lib = Library()
print(lib.find("Dune").pages)Traceback (most recent call last):
File "/Users/you/python-course/library.py", line 9, in <module>
print(lib.find("Dune").pages)
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'pages'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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06לתכנן מחלקהDesigning a class
טריק פשוט לתכנון: כותבים במשפט מה התוכנית עושה. שמות עצם (ספר, ספרייה, כותרת) הופכים למחלקות ולתכונות, ופעלים (להוסיף, לקרוא, לחפש) הופכים למתודות. שמות מחלקות כותבים ב-CamelCase: ReadingGoal, ושמות מתודות ב-snake_case.
A simple design trick: write in a sentence what the program does. Nouns (book, library, title) become classes and attributes, verbs (add, read, search) become methods. Class names use CamelCase: ReadingGoal, method names snake_case.
class ReadingGoal:
"""A yearly goal: read N books."""
def __init__(self, year, target):
self.year = year
self.target = target
self.done = []
def finish(self, title):
self.done.append(title)
def left(self):
return max(self.target - len(self.done), 0)
def report(self):
return f"{self.year}: {len(self.done)}/{self.target}, {self.left()} to go"
goal = ReadingGoal(2026, 12)
for t in ["Dune", "Emma", "Matilda"]:
goal.finish(t)
print(goal.report())2026: 3/12, 9 to go
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
לתכנן מחלקה זה כמו לתכנן טופס: קודם מחליטים אילו שדות יש (תכונות), ואחר כך אילו כפתורים (מתודות).
Designing a class is like designing a form: first decide the fields (attributes), then the buttons (methods).
קוראים למתודה בלי סוגריים ומקבלים את המתודה עצמה.
Calling a method without parentheses gives you the method itself.
class Goal:
def __init__(self):
self.done = 3
def left(self):
return 12 - self.done
g = Goal()
print(g.left + 1)Traceback (most recent call last):
File "/Users/you/python-course/goal.py", line 9, in <module>
print(g.left + 1)
~~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'method' and 'int'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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.