לדלג לתוכן

5.4 אנקפסולציה פתרון

מערכת בנקאית 2

class BankAccount:
    def __init__(self):
        self._balance = 0

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

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("Balance cannot be negative")
        else:
            self._balance = value

# Test the implementation
account = BankAccount()
print(account.balance)  # Output: 0
account.balance = 100
print(account.balance)  # Output: 100
try:
    account.balance = -50  # Raises ValueError
except ValueError as e:
    print(e)  # Output: Balance cannot be negative

בן אדם

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    email: str

# Test the implementation
person1 = Person("Alice", 30, "alice@example.com")
person2 = Person("Bob", 25, "bob@example.com")
print(person1)  # Output: Person(name=Alice, age=30, email=alice@example.com)
print(person2)  # Output: Person(name=Bob, age=25, email=bob@example.com)