descriptor
In Python, a descriptor is an object attribute with binding behavior, meaning that its behavior is triggered when you access, set, or delete an attribute. Descriptors are a powerful feature that allows you to customize the way attributes are accessed or modified in your classes.
To create a descriptor, you implement the descriptor protocol methods: .__get__()
, .__set__()
, and .__delete__()
. With these methods, you can control the attribute’s behavior when you access, modify, or delete it.
Note: In practice, to define a descriptor, you only need to implement the .__get__()
method. The other two methods are optional and you’ll implement them only when needed.
Descriptors let you manage the attributes of classes in a more controlled manner. Common use cases of descriptors include enforcing type checking, data validation, and implementing lazy attributes.
Example
Here’s a simple example to illustrate how a descriptor works:
class Coordinate:
def __set_name__(self, owner, name):
self._name = name
def __get__(self, instance, owner):
return instance.__dict__[self._name]
def __set__(self, instance, value):
try:
instance.__dict__[self._name] = float(value)
print("Validated!")
except ValueError:
raise ValueError(f'"{self._name}" must be a number') from None
class Point:
x = Coordinate()
y = Coordinate()
def __init__(self, x, y):
self.x = x
self.y = y
In this example, you define the Coordinate
descriptor to validate and convert coordinate values to floats in the Point
class. The Point
class uses two Coordinate
instances (.x
and .y
) to enforce numeric values for its .x
and .y
coordinates. It raises an error if you pass invalid values.
Related Resources
Tutorial
Python Descriptors: An Introduction
In this step-by-step tutorial, you'll learn what Python descriptors are and how they're used in Python's internals. You'll learn about the descriptor protocol and how the lookup chain works when you access an attribute. You'll also see a few practical examples where Python descriptors can come in handy.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)