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

single

Challenge: Type-Enforced Data Model

Glissez pour afficher le menu

Tâche

Glissez pour commencer à coder

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.

Solution

Switch to desktopPassez à un bureau pour une pratique réelleContinuez d'où vous êtes en utilisant l'une des options ci-dessous
Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 4
single

single

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

some-alt