Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 11 · Decorator patterns at scaleDescriptor protocol — the mechanic under @property and ORM columnspredict155 / 161
+150 XP
Task
📝 **Task:** Predict the 4-line output. A `Positive` descriptor validates that assignments are positive ints. The `Account` class uses it for two attributes (balance + age). Test: normal set + get works, negative value triggers ValueError, class-level access returns the descriptor itself (not the value), per-instance values are independent. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

class Positive:
    def __set_name__(self, owner, name: str) -> None:
        self.name = name

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value) -> None:
        if not isinstance(value, int) or value <= 0:
            raise ValueError(f"{self.name} must be positive int, got {value!r}")
        instance.__dict__[self.name] = value


class Account:
    balance = Positive()
    age = Positive()


a = Account()
a.balance = 100
a.age = 30
print(a.balance, a.age)

try:
    a.balance = -5
except ValueError as e:
    print(f"rejected: {e}")

# Class-level access returns the descriptor itself, not a value
print(type(Account.balance).__name__)

# Per-instance values are independent
b = Account()
b.balance = 200
print(a.balance, b.balance)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…