Секція 1. Розділ 4
single
Challenge: Your First Descriptor
Свайпніть щоб показати меню
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
Завдання
Проведіть, щоб почати кодувати
- 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.
Рішення
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 1. Розділ 4
single
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат