Descriptor is an object that defines methods for getting, setting, and deleting attributes. They are a way to customize attribute access in classes.
It is any object that implements one or more of the following methods:
__get__(self, instance, owner)
__set__(self, instance, value)
__delete__(self, instance)
A common use case for descriptors is to manage the access to attributes in a class. For example, they can be used to create properties, manage lazy loading, or implement computed attributes.
Let’s see an example with lazy loading with AI model.
import time
class LazyModelTrainingDescriptor:
def __init__(self, model_name):
self.model_name = model_name
self.model = None
self.trained = False
def __get__(self, obj, objtype=None):
if not self.model:
print(f"Initializing and training '{self.model_name}' model...")
self.model = self.train_model()
self.trained = True
else:
print(f"Using cached '{self.model_name}' model...")
return self.model
def train_model(self):
# Simulating model training which takes time
time.sleep(5) # Simulate training time
return…