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

single

Challenge: Your First Descriptor

Scorri per mostrare il 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
Compito

Scorri per iniziare a programmare

  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.

Soluzione

Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 4
single

single

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt