single
Challenge: Type-Enforced Data Model
Sveip for å vise menyen
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.
-
Implement a base class
Validatorwith:__set_name__(self, owner, name)that stores the attribute name inself._name;__get__(self, obj, objtype=None)that returnsselfwhenobj is None, otherwise returnsobj.__dict__.get(self._name);__set__(self, obj, value)that callsself.validate(self._name, value)and then stores the value inobj.__dict__[self._name];- an abstract
validate(self, name, value)method that raisesNotImplementedError.
-
Implement
PositiveFloat(Validator)whosevalidateraisesValueErrorifvalueis not a positiveintorfloat. -
Implement
NonEmptyString(Validator)whosevalidateraisesValueErrorifvalueis not a non-empty string after stripping whitespace. -
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 -
Create a
Tradeinstance calledtradewithticker="AAPL",quantity=50.0,price=189.50. -
Create an
Accountinstance calledaccountwithaccount_id="ACC-001",balance=10000.0. -
Print
trade.ticker,trade.quantity,account.account_id, andaccount.balance.
Løsning
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår