Sobes.tech
Junior — Middle

Explain what the term 'descriptor' means in the context of the Python language and how it works.

sobes.tech AI

Answer from AI

In Python, the term "descriptor" refers to an object that manages access to the attributes of another object. Descriptors implement the methods __get__, __set__, and __delete__, which are called when an attribute is read, written, or deleted respectively.

This allows controlling the behavior of attributes, for example, implementing computed properties, validation, or lazy initialization.

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  # calls __set__
print(obj.attr)  # calls __get__

Thus, descriptors allow encapsulating access logic to attributes and are widely used in Python, for example, in properties (@property), class methods, and metaclasses.

Explain what the term 'descriptor' means in the… - sobes.tech