Sobes.tech
Junior — Middle

Explain the purpose and operation of the __set__() method in a Python descriptor class.

sobes.tech AI

Answer from AI

The __set__() method in a Python descriptor class is responsible for intercepting the assignment of a value to an object's attribute. When an attribute implemented via a descriptor is assigned a value, this method is called.

It takes three parameters:

  • self — the descriptor instance,
  • instance — the object to which the attribute is being assigned,
  • value — the new value.

Example usage:

class Descriptor:
    def __set__(self, instance, value):
        print(f"Setting value {value} for {instance}")
        instance._value = value

class MyClass:
    attr = Descriptor()

obj = MyClass()
obj.attr = 42  # calls Descriptor.__set__(obj, 42)

Thus, __set__() allows controlling the process of setting a value, for example, for validation, logging, or access control.