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

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

Dataclasses ו-type hintsDataclasses & type hints

@dataclass, רמזי טיפוסים ובדיקה עם mypy.

@dataclass, type hints and checking with mypy.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה קורה כשמעבירים "5" לפונקציה עם n: int?What happens when you pass "5" to a function with n: int?

2. מה @dataclass כותב בשבילכם?What does @dataclass write for you?

3. איך כותבים ברירת מחדל של רשימה ריקה ב-dataclass?How do you write an empty-list default in a dataclass?

תרגיליםExercises

תרגילExercise 1

להוסיף רמזיםAdd hints

הוסיפו רמזי טיפוס לכל הפרמטרים ולערכי ההחזרה: average(nums) מקבלת רשימת float ומחזירה float, ו-greet(name, times) מקבלת str ו-int ומחזירה str.

Add type hints to every parameter and return value: average(nums) takes a list of float and returns float, and greet(name, times) takes str and int and returns str.

איך הפלט אמור להיראות?What should the output look like?
5.0
Hi Noa! Hi Noa!
main.py
רמזHint 1: def average(nums: list[float]) -> float:def average(nums: list[float]) -> float:
רמזHint 2: def greet(name: str, times: int) -> str:def greet(name: str, times: int) -> str:
לפתרוןSolution
תרגילExercise 2

מוצר כ-dataclassA product dataclass

כתבו dataclass Product עם name: str, price: float, qty: int = 1, ומתודה total() שמחזירה מחיר × כמות. הדפיסו את המוצר ואת total().

Write a Product dataclass with name: str, price: float, qty: int = 1, and a total() method returning price × qty. Print the product and total().

איך הפלט אמור להיראות?What should the output look like?
Product(name='pen', price=4.5, qty=3)
13.5
main.py
רמזHint 1: @dataclass מעל class Product:.@dataclass above class Product:.
רמזHint 2: qty: int = 1 אחרון.qty: int = 1 last.
לפתרוןSolution
תרגילExercise 3

רשימת תגיםA tag list

כתבו dataclass Note עם text: str ו-tags: list[str] שמתחילה ריקה (בצורה הנכונה!), ומתודה tag(t) שמוסיפה תג רק אם הוא לא קיים כבר.

Write a Note dataclass with text: str and tags: list[str] starting empty (the right way!), and a tag(t) method that adds a tag only if it isn't there already.

איך הפלט אמור להיראות?What should the output look like?
['home'] []
main.py
רמזHint 1: tags: list[str] = field(default_factory=list)tags: list[str] = field(default_factory=list)
רמזHint 2: if t not in self.tags:if t not in self.tags:
לפתרוןSolution
תרגילExercise 4

ציונים מסודריםOrdered grades

כתבו dataclass Grade עם order=True ושדות score: int, name: str (בסדר הזה, כדי שהמיון יהיה לפי ציון). הדפיסו את שמות הסטודנטים מהציון הגבוה לנמוך.

Write a Grade dataclass with order=True and fields score: int, name: str (in that order, so sorting is by score). Print the student names from highest to lowest score.

איך הפלט אמור להיראות?What should the output look like?
['Avi', 'Dana', 'Noa']
main.py
רמזHint 1: @dataclass(order=True)@dataclass(order=True)
רמזHint 2: [g.name for g in sorted(grades, reverse=True)][g.name for g in sorted(grades, reverse=True)]
לפתרוןSolution
תרגילExercise 5

מדף, צעד 18: Book כ-dataclassShelf, step 18: Book as a dataclass

פרויקט מלווהCompanion project

כתבו את Book מחדש כ-dataclass עם רמזים: title: str, author: str, pages: int, read: int = 0, tags: list[str] ריקה. הוסיפו progress() -> int (אחוז מעוגל). כתבו find(shelf: list[Book], title: str) -> Book | None. הדפיסו את asdict של הספר שנמצא.

Rewrite Book as a dataclass with hints: title: str, author: str, pages: int, read: int = 0, tags: list[str] empty. Add progress() -> int (rounded percent). Write find(shelf: list[Book], title: str) -> Book | None. Print asdict of the found book.

איך הפלט אמור להיראות?What should the output look like?
25 {'title': 'Dune', 'author': 'Frank Herbert', 'pages': 412, 'read': 103, 'tags': []}
shelf.py
רמזHint 1: from dataclasses import dataclass, field, asdictfrom dataclasses import dataclass, field, asdict
רמזHint 2: return round(self.read / self.pages * 100)return round(self.read / self.pages * 100)
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

עגלת קניות מוקלדתA typed cart

כתבו dataclass Item(name: str, price: float) עם frozen=True, ו-dataclass Cart עם items: dict[str, int] (שם → כמות), catalog: dict[str, Item], ומתודות add(name, qty=1) (ValueError אם השם לא בקטלוג), remove(name) ו-total() -> float מעוגל ל-2.

Write a frozen dataclass Item(name: str, price: float), and a Cart dataclass with items: dict[str, int] (name → qty), catalog: dict[str, Item], and methods add(name, qty=1) (ValueError if the name isn't in the catalog), remove(name) and total() -> float rounded to 2.

איך הפלט אמור להיראות?What should the output look like?
73.4
main.py
רמזHint 1: items: dict[str, int] = field(default_factory=dict)items: dict[str, int] = field(default_factory=dict)
רמזHint 2: sum(self.catalog[n].price * q for n, q in self.items.items())sum(self.catalog[n].price * q for n, q in self.items.items())
לפתרוןSolution
אתגרChallenge 2

מ-dict ל-dataclassFrom dict to dataclass

כתבו from_dict(cls, data) כללית: יוצרת אובייקט של dataclass כלשהי ממילון, תוך התעלמות ממפתחות שאינם שדות, והמרה של כל ערך לטיפוס של השדה (למשל "412" → 412). השתמשו ב-dataclasses.fields(cls) וב-f.type.

Write a generic from_dict(cls, data): creates an object of any dataclass from a dict, ignoring keys that aren't fields and converting each value to the field's type (e.g. "412" → 412). Use dataclasses.fields(cls) and f.type.

איך הפלט אמור להיראות?What should the output look like?
Book(title='Dune', pages=412, rating=4.5)
main.py
רמזHint 1: {f.name: f.type(data[f.name]) for f in fields(cls) if f.name in data}{f.name: f.type(data[f.name]) for f in fields(cls) if f.name in data}
רמזHint 2: return cls(**kwargs)return cls(**kwargs)
לפתרוןSolution

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