Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Challenge: Reimplementing property | Descriptors in the Wild
Python Descriptors Explained
セクション 2.  5
single

single

Challenge: Reimplementing property

メニューを表示するにはスワイプしてください

You are going to build a simplified version of Python's built-in property from scratch using the descriptor protocol. This will cement your understanding of how property works under the hood.

Your SimpleProperty descriptor must support a getter, an optional setter, and an optional deleter – matching the interface of the built-in property.

タスク

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

  1. Implement a class SimpleProperty with:
    • __init__(self, fget=None, fset=None, fdel=None) that stores all three functions;
    • __get__(self, obj, objtype=None) that returns self when obj is None, raises AttributeError if fget is None, otherwise calls and returns fget(obj);
    • __set__(self, obj, value) that raises AttributeError if fset is None, otherwise calls fset(obj, value);
    • __delete__(self, obj) that raises AttributeError if fdel is None, otherwise calls fdel(obj);
    • a setter(self, fset) method that returns a new SimpleProperty with the same fget and fdel but the new fset;
    • a deleter(self, fdel) method that returns a new SimpleProperty with the same fget and fset but the new fdel.
  2. Apply SimpleProperty to the Portfolio class below:
    • decorate value with @SimpleProperty as the getter;
    • use @value.setter to add a setter that stores the value in self._value if it is non-negative, otherwise raises ValueError;
    • use @value.deleter to add a deleter that sets self._value to 0.0.
  3. Create an instance called portfolio with portfolio_id="PF-001" and value=50000.0.
  4. Store portfolio.value in a variable called initial_value.
  5. Set portfolio.value to 75000.0, then store the new value in updated_value.
  6. Print initial_value and updated_value.
class Portfolio:
    def __init__(self, portfolio_id, value):
        self.portfolio_id = portfolio_id
        self._value = value

解答

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

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

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

セクション 2.  5
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt