Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Challenge: Reimplementing property | Descriptors in the Wild
Python Descriptors Explained
Sectie 2. Hoofdstuk 5
single

single

Challenge: Reimplementing property

Veeg om het menu te tonen

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.

Taak

Veeg om te beginnen met coderen

  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

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 2. Hoofdstuk 5
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