Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Reimplementing property | Descriptors in the Wild
Python Descriptors Explained
Sektion 2. Kapitel 5
single

single

Challenge: Reimplementing property

Stryg for at vise menuen

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.

Opgave

Swipe to start coding

  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

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 5
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt