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

single

Challenge: Your First Descriptor

Veeg om het menu te tonen

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
Taak

Veeg om te beginnen met coderen

  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.

Oplossing

Switch to desktopSchakel over naar desktop voor praktijkervaringGa verder vanaf waar je bent met een van de onderstaande opties
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 4
single

single

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt