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

PythonPython

מבחן 4: תכנות מונחה עצמיםExam 4: Object-oriented programming

מחלקות, ירושה, מתודות קסם, dataclasses ו-property

Classes, inheritance, magic methods, dataclasses and property

75 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
75:00השעון רק עוזר להתאמן. אפשר גם בלי.The timer is just for practice. You can skip it.

חלק א: שאלות בחירה (5 נקודות לשאלה)Part A: multiple choice (5 points each)

התשובות מתגלות רק כשמסיימים את המבחן.Answers are revealed only when you finish the exam.

1. מה יודפס?What is printed? 5
python
class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof"

print(Dog().speak())
2. איזו מתודה קובעת מה print(obj) מציג?Which method decides what print(obj) shows? 5
3. מה ההבדל בין משתנה מחלקה למשתנה מופע?What's the difference between a class variable and an instance variable? 5
4. מה @dataclass יוצר אוטומטית?What does @dataclass create automatically? 5

חלק ב: שאלות קודPart B: coding questions

שאלהQuestion 5

חשבון בנקA bank account

כתבו Account(owner, balance=0) עם deposit(x) ו-withdraw(x). סכום לא חיובי זורק ValueError("amount must be positive"); משיכה גדולה מהיתרה זורקת ValueError("insufficient funds"). history היא רשימת טאפלים ("in"/"out", amount). balance הוא property לקריאה בלבד.

Write Account(owner, balance=0) with deposit(x) and withdraw(x). A non-positive amount raises ValueError("amount must be positive"); withdrawing more than the balance raises ValueError("insufficient funds"). history is a list of ("in"/"out", amount) tuples. balance is a read-only property.

איך הפלט אמור להיראות?What should the output look like?
insufficient funds
70 [('in', 100), ('out', 30)]
main.py
רמזHint 1: self._balance.self._balance.
רמזHint 2: פונקציית עזר _check(x).A helper _check(x).
הפתרון שלנוOur solution
main.py
class Account:
    def __init__(self, owner, balance=0):
        self.owner, self._balance, self.history = owner, balance, []

    @property
    def balance(self):
        return self._balance

    def _check(self, x):
        if x <= 0:
            raise ValueError("amount must be positive")

    def deposit(self, x):
        self._check(x)
        self._balance += x
        self.history.append(("in", x))

    def withdraw(self, x):
        self._check(x)
        if x > self._balance:
            raise ValueError("insufficient funds")
        self._balance -= x
        self.history.append(("out", x))

a = Account("Noa")
a.deposit(100)
a.withdraw(30)
try:
    a.withdraw(500)
except ValueError as e:
    print(e)
print(a.balance, a.history)
פלטOutput
insufficient funds
70 [('in', 100), ('out', 30)]

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (30 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 6

צורותShapes

כתבו מחלקת בסיס Shape עם area() שזורקת NotImplementedError, ו-__lt__ שמשווה לפי שטח. כתבו Rect(w, h) ו-Circle(r) (שטח 3.14159 * r * r). largest(shapes) מחזירה את הצורה עם השטח הגדול (בעזרת max).

Write a base class Shape with area() raising NotImplementedError, and __lt__ comparing by area. Write Rect(w, h) and Circle(r) (area 3.14159 * r * r). largest(shapes) returns the shape with the biggest area (using max).

איך הפלט אמור להיראות?What should the output look like?
Rect 12
main.py
רמזHint 1: עם __lt__, max עובד בלי key.With __lt__, max works without a key.
הפתרון שלנוOur solution
main.py
class Shape:
    def area(self):
        raise NotImplementedError

    def __lt__(self, other):
        return self.area() < other.area()

class Rect(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14159 * self.r * self.r

def largest(shapes):
    return max(shapes)

big = largest([Rect(3, 4), Circle(1.5), Rect(1, 10)])
print(type(big).__name__, round(big.area(), 2))
פלטOutput
Rect 12

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 7

מלאי עם dataclassInventory with a dataclass

כתבו @dataclass Item(name: str, price: float, qty: int = 0) עם total() (מחיר כפול כמות), ו-order=True כך שאפשר למיין פריטים (לפי name, אחר כך price). כתבו cheapest_in_stock(items) שמחזירה את שם הפריט הזול ביותר שיש ממנו לפחות 1, או None.

Write @dataclass Item(name: str, price: float, qty: int = 0) with total() (price times quantity), and order=True so items can be sorted (by name, then price). Write cheapest_in_stock(items) returning the name of the cheapest item with at least 1 in stock, or None.

איך הפלט אמור להיראות?What should the output look like?
Item(name='cap', price=3.0, qty=2) cap 51.0
main.py
רמזHint 1: @dataclass(order=True).@dataclass(order=True).
רמזHint 2: min(..., key=..., default=None).min(..., key=..., default=None).
הפתרון שלנוOur solution
main.py
from dataclasses import dataclass

@dataclass(order=True)
class Item:
    name: str
    price: float
    qty: int = 0

    def total(self):
        return self.price * self.qty

def cheapest_in_stock(items):
    best = min((i for i in items if i.qty > 0), key=lambda i: i.price, default=None)
    return best.name if best else None

items = [Item("pen", 4.5, 10), Item("ink", 2.0, 0), Item("cap", 3.0, 2)]
print(sorted(items)[0], cheapest_in_stock(items), sum(i.total() for i in items))
פלטOutput
Item(name='cap', price=3.0, qty=2) cap 51.0

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

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