Code

Descriptors

A descriptor is an object stored on a class that controls what happens when you get or set that attribute on an instance. It's any object with __get__ (and usually __set__):

  • __set_name__(self, owner, name): called once when the class is created, telling the descriptor its attribute name.
  • __get__(self, obj, objtype): runs for obj.attr. When accessed on the class itself, obj is None.
  • __set__(self, obj, value): runs for obj.attr = value.
class Upper:
    def __set_name__(self, owner, name):
        self.private = "_" + name
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private)
    def __set__(self, obj, value):
        setattr(obj, self.private, value.upper())

class Ship:
    name = Upper()      # one descriptor, shared by all ships

s = Ship()
s.name = "wren"     # Upper.__set__ runs
s.name              # 'WREN'

You've used descriptors all along: @property builds one, and plain methods are descriptors too (that's how self gets bound). A descriptor with __set__ takes priority over the instance's own __dict__, which is why validation can't be skipped.

Assignment

Finish the reusable Positive descriptor:

  1. __get__ returns the value stored on the instance under self.private: or the descriptor itself when obj is None.
  2. __set__ raises ValueError(f"{self.public} must be positive") if value <= 0; otherwise stores it on the instance.