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

single

Challenge: Reimplementing property

Scorri per mostrare il menu

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.

Compito

Scorri per iniziare a programmare

  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

Soluzione

Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 5
single

single

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt