Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Challenge: Your First Descriptor | What Descriptors Are
Python Descriptors Explained
セクション 1.  4
single

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
タスク

スワイプしてコーディングを開始

  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.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  4
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt