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

single

Challenge: Type-Enforced Data Model

Sveip for å vise menyen

Oppgave

Sveip for å begynne å kode

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.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 4
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt