Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Challenge: Type-Enforced Data Model | Building Useful Descriptors
Python Descriptors Explained
Sectie 3. Hoofdstuk 4
single

single

Challenge: Type-Enforced Data Model

Veeg om het menu te tonen

Taak

Veeg om te beginnen met coderen

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.

Oplossing

Switch to desktopSchakel over naar desktop voor praktijkervaringGa verder vanaf waar je bent met een van de onderstaande opties
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 4
single

single

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt