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 behavior
1class Positive:
# __set_name__ is called when descriptor is assigned to class
# owner is the class (Account), name is the attribute name
2 def __set_name__(self, owner, name):
# Store the attribute name for later use
3 self.name = name
4
# __get__ is called when accessing the attribute
# obj is the instance, objtype is the class
5 def __get__(self, obj, objtype=None):
# Get value from instance's __dict__, default 0
6 return obj.__dict__.get(self.name, 0)
7
# __set__ is called when assigning to the attribute
# value is the new value being assigned
8 def __set__(self, obj, value):
# Validate that value is not negative
9 if value < 0:
# Raise error with descriptive message
10 raise ValueError(f"{self.name} must be positive")
# Store valid value in instance's __dict__
11 obj.__dict__[self.name] = value
12
# class Account uses the Positive descriptor
# balance will be validated automatically
13class Account:
# balance is a class attribute using Positive descriptor
14 balance = Positive()
15
# Create Account instance
16a = Account()
# a.balance = 100 calls Positive.__set__
# Value is valid, so it's stored
17a.balance = 100
# a.balance calls Positive.__get__
# Returns 100 from instance __dict__
18print(a.balance)

Output

100
Practice typing this code

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

More Python examples at level 5

← Python typing practice