Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Challenge: Your First Descriptor | What Descriptors Are
Python Descriptors Explained
Section 1. Chapitre 4
single

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

  1. Implement BoundedFloat as a data descriptor with:
    • __init__(self, min_value, max_value) that stores min_value and max_value;
    • __set_name__(self, owner, name) that stores the attribute name in self._name;
    • __get__(self, obj, objtype=None) that returns self when obj is None, otherwise returns obj.__dict__.get(self._name);
    • __set__(self, obj, value) that raises TypeError if value is not a float or int, and ValueError if value is outside [min_value, max_value], otherwise stores it in obj.__dict__[self._name].
  2. Create a Position instance called position with ticker="AAPL", quantity=100.0, price=189.50.
  3. Store the result of position.quantity in a variable called qty.
  4. Store the result of position.price in a variable called prc.
  5. Print qty and prc.

Solution

Switch to desktopPassez à un bureau pour une pratique réelleContinuez d'où vous êtes en utilisant l'une des options ci-dessous
Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 4
single

single

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

some-alt