Sobes.tech
Middle

What is the main function of descriptors in Python?

sobes.tech AI

Answer from AI

Descriptors in Python are objects that control access to attributes of other objects. The main function of descriptors is to override behavior when reading, writing, and deleting attributes through the __get__, __set__, and __delete__ methods.

This allows implementing properties, data validation, lazy initialization, and other mechanisms for controlling access to data.

Example of a simple descriptor:

class Descriptor:
    def __get__(self, instance, owner):
        return instance._value
    def __set__(self, instance, value):
        if value < 0:
            raise ValueError("Value cannot be negative")
        instance._value = value

class MyClass:
    attr = Descriptor()

obj = MyClass()
obj.attr = 10  # works
# obj.attr = -5  # will raise ValueError