Seção 1. Capítulo 4
single
Challenge: Your First Descriptor
Deslize para mostrar o menu
You are building a data model for a financial application. Your task is to implement a validated descriptor that enforces type and range constraints on numeric attributes.
You are given the following class skeleton:
class BoundedFloat:
pass
class Position:
quantity = BoundedFloat(min_value=0.0, max_value=10000.0)
price = BoundedFloat(min_value=0.01, max_value=999999.99)
def __init__(self, ticker, quantity, price):
self.ticker = ticker
self.quantity = quantity
self.price = price
Tarefa
Deslize para começar a programar
- Implement
BoundedFloatas a data descriptor with:__init__(self, min_value, max_value)that storesmin_valueandmax_value;__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 raisesTypeErrorifvalueis not afloatorint, andValueErrorifvalueis outside[min_value, max_value], otherwise stores it inobj.__dict__[self._name].
- Create a
Positioninstance calledpositionwithticker="AAPL",quantity=100.0,price=189.50. - Store the result of
position.quantityin a variable calledqty. - Store the result of
position.pricein a variable calledprc. - Print
qtyandprc.
Solução
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 1. Capítulo 4
single
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo