single
Challenge: Type-Enforced Data Model
Desliza para mostrar el menú
Desliza para comenzar a programar
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.
Solución
¡Gracias por tus comentarios!
single
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla