Dataclasses ו-type hintsDataclasses & type hints
@dataclass, רמזי טיפוסים ובדיקה עם mypy.
@dataclass, type hints and checking with mypy.
להוסיף רמזיםAdd hints
תזכורת: מה ביקשוReminder: the task
הוסיפו רמזי טיפוס לכל הפרמטרים ולערכי ההחזרה: 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.
הפתרון המלא והפלט שלוFull solution and its output
def average(nums: list[float]) -> float:
return sum(nums) / len(nums)
def greet(name: str, times: int) -> str:
return ("Hi " + name + "! ") * times
print(average([4.5, 5.5]))
print(greet("Noa", 2))5.0 Hi Noa! Hi Noa!
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מוצר כ-dataclassA product dataclass
תזכורת: מה ביקשוReminder: the task
כתבו 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().
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
qty: int = 1
def total(self) -> float:
return self.price * self.qty
p = Product("pen", 4.5, 3)
print(p)
print(p.total())Product(name='pen', price=4.5, qty=3) 13.5
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
רשימת תגיםA tag list
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass, field
@dataclass
class Note:
text: str
tags: list[str] = field(default_factory=list)
def tag(self, t: str) -> None:
if t not in self.tags:
self.tags.append(t)
a = Note("buy milk")
b = Note("call mom")
a.tag("home")
a.tag("home")
print(a.tags, b.tags)['home'] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ציונים מסודריםOrdered grades
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass
@dataclass(order=True)
class Grade:
score: int
name: str
grades = [Grade(82, "Dana"), Grade(95, "Avi"), Grade(70, "Noa")]
print([g.name for g in sorted(grades, reverse=True)])['Avi', 'Dana', 'Noa']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 18: Book כ-dataclassShelf, step 18: Book as a dataclass
תזכורת: מה ביקשוReminder: the task
כתבו את 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.
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass, field, asdict
@dataclass
class Book:
title: str
author: str
pages: int
read: int = 0
tags: list[str] = field(default_factory=list)
def progress(self) -> int:
return round(self.read / self.pages * 100)
def find(shelf: list[Book], title: str) -> Book | None:
for b in shelf:
if b.title.lower() == title.lower():
return b
return None
shelf = [Book("Dune", "Frank Herbert", 412, 103), Book("Emma", "Jane Austen", 474)]
found = find(shelf, "dune")
if found is not None:
print(found.progress(), asdict(found))25 {'title': 'Dune', 'author': 'Frank Herbert', 'pages': 412, 'read': 103, 'tags': []}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עגלת קניות מוקלדתA typed cart
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Item:
name: str
price: float
@dataclass
class Cart:
catalog: dict[str, Item]
items: dict[str, int] = field(default_factory=dict)
def add(self, name: str, qty: int = 1) -> None:
if name not in self.catalog:
raise ValueError(f"unknown item: {name}")
self.items[name] = self.items.get(name, 0) + qty
def remove(self, name: str) -> None:
self.items.pop(name, None)
def total(self) -> float:
return round(sum(self.catalog[n].price * q for n, q in self.items.items()), 2)
catalog = {i.name: i for i in [Item("pen", 4.5), Item("book", 59.9)]}
cart = Cart(catalog)
cart.add("pen", 3)
cart.add("book")
print(cart.total())73.4
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מ-dict ל-dataclassFrom dict to dataclass
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass, fields
@dataclass
class Book:
title: str
pages: int
rating: float = 0.0
def from_dict(cls, data):
kwargs = {f.name: f.type(data[f.name]) for f in fields(cls) if f.name in data}
return cls(**kwargs)
row = {"title": "Dune", "pages": "412", "rating": "4.5", "isbn": "x"}
print(from_dict(Book, row))Book(title='Dune', pages=412, rating=4.5)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.