Descriptor Protocol in Python
Level 5330 keystrokes
This implements the descriptor protocol for attribute validation. __get__ and __set__ control attribute access on instances.
Python code
# Define descriptor class for validation1class Validator: # Called when descriptor is assigned to class attribute2 def __set_name__(self, owner, name): # Store the attribute name3 self.name = name # Called when getting the attribute value4 def __get__(self, obj, type=None): # Return value from instance dict5 return obj.__dict__.get(self.name) # Called when setting the attribute value6 def __set__(self, obj, value): # Validate the value is non-negative7 if value < 0: # Raise error for invalid value8 raise ValueError("Must be >= 0") # Store value in instance dict9 obj.__dict__[self.name] = value10 # Class using the descriptor11class Product: # price attribute uses Validator descriptor12 price = Validator()13 # Create Product instance14p = Product()# Set price through descriptor15p.price = 100# Get price through descriptor16print(p.price)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.× 8(× 8)× 8=× 7,× 6:× 6"× 2[× 1]× 1