Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Reimplementing property | Descriptors in the Wild
Python Descriptors Explained
Sección 2. Capítulo 5
single

single

Challenge: Reimplementing property

Desliza para mostrar el menú

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.

Tarea

Desliza para comenzar a programar

  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

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 5
single

single

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt