Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Your First Descriptor | What Descriptors Are
Python Descriptors Explained
Sektion 1. Kapitel 4
single

single

Challenge: Your First Descriptor

Stryg for at vise menuen

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
Opgave

Swipe to start coding

  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.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 4
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt