Custom Descriptor in Python
Level 5359 keystrokes
This creates a descriptor that rejects negative values. Descriptors control attribute access using __get__, __set__, and __set_name__.
Python code
# class Positive is a descriptor that rejects negative values (0 is allowed)# Descriptors customize attribute access behavior1class Positive: # __set_name__ is called when descriptor is assigned to class # owner is the class (Account), name is the attribute name2 def __set_name__(self, owner, name): # Store the attribute name for later use3 self.name = name4 # __get__ is called when accessing the attribute # obj is the instance, objtype is the class5 def __get__(self, obj, objtype=None): # Get value from instance's __dict__, default 06 return obj.__dict__.get(self.name, 0)7 # __set__ is called when assigning to the attribute # value is the new value being assigned8 def __set__(self, obj, value): # Validate that value is not negative9 if value < 0: # Raise error with descriptive message10 raise ValueError(f"{self.name} must be positive") # Store valid value in instance's __dict__11 obj.__dict__[self.name] = value12 # class Account uses the Positive descriptor# balance will be validated automatically13class Account: # balance is a class attribute using Positive descriptor14 balance = Positive()15 # Create Account instance16a = Account()# a.balance = 100 calls Positive.__set__# Value is valid, so it's stored17a.balance = 100# a.balance calls Positive.__get__# Returns 100 from instance __dict__18print(a.balance)Output
100
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 21.× 9(× 8)× 8,× 7:× 6=× 6"× 2[× 1]× 1