Section 1. Chapitre 4
single
Challenge: Your First Descriptor
Glissez pour afficher le 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
Tâche
Glissez pour commencer à coder
- 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.
Solution
Tout était clair ?
Merci pour vos commentaires !
Section 1. Chapitre 4
single
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion