
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 forobj.attr. When accessed on the class itself,objisNone.__set__(self, obj, value): runs forobj.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:
__get__returns the value stored on the instance underself.private: or the descriptor itself whenobjisNone.__set__raisesValueError(f"{self.public} must be positive")ifvalue <= 0; otherwise stores it on the instance.
Finish the reusable Positive descriptor:
__get__returns the value stored on the instance underself.private: or the descriptor itself whenobjisNone.__set__raisesValueError(f"{self.public} must be positive")ifvalue <= 0; otherwise stores it on the instance.
main.py Python sleeping
Press Run to try your code, then Check to test it.