Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Challenge: Type-Enforced Data Model | Building Useful Descriptors
Python Descriptors Explained
Секція 3. Розділ 4
single

single

Challenge: Type-Enforced Data Model

Свайпніть щоб показати меню

Завдання

Проведіть, щоб почати кодувати

You are building a reusable validation layer for a financial data model. Your task is to implement a descriptor hierarchy and apply it to two classes.

  1. Implement a base class Validator with:

    • __set_name__(self, owner, name) that stores the attribute name in self._name;
    • __get__(self, obj, objtype=None) that returns self when obj is None, otherwise returns obj.__dict__.get(self._name);
    • __set__(self, obj, value) that calls self.validate(self._name, value) and then stores the value in obj.__dict__[self._name];
    • an abstract validate(self, name, value) method that raises NotImplementedError.
  2. Implement PositiveFloat(Validator) whose validate raises ValueError if value is not a positive int or float.

  3. Implement NonEmptyString(Validator) whose validate raises ValueError if value is not a non-empty string after stripping whitespace.

  4. Apply the descriptors to the following two classes:

     class Trade:
         # ticker: NonEmptyString
         # quantity: PositiveFloat
         # price: PositiveFloat
         def __init__(self, ticker, quantity, price):
             self.ticker = ticker
             self.quantity = quantity
             self.price = price
     
     class Account:
         # account_id: NonEmptyString
         # balance: PositiveFloat
         def __init__(self, account_id, balance):
             self.account_id = account_id
             self.balance = balance
    
  5. Create a Trade instance called trade with ticker="AAPL", quantity=50.0, price=189.50.

  6. Create an Account instance called account with account_id="ACC-001", balance=10000.0.

  7. Print trade.ticker, trade.quantity, account.account_id, and account.balance.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt