Sobes.tech
Junior — Middle

Kas saaksite selgitada __delete__() meetodi eesmärki Python descriptoris ja kuidas see töötab?

sobes.tech AI

Vastus AI-lt

The __delete__() method in a Python descriptor is responsible for deleting an attribute from the object to which the descriptor is applied.

A descriptor is an object that implements the __get__(), __set__(), and/or __delete__() methods, and manages access to the attributes of another object.

When del instance.attr is called, and attr is a descriptor with a __delete__() method, this method is invoked with the argument instance, which is the object from which the attribute is being deleted.

Example:

class Descriptor:
    def __delete__(self, instance):
        print(f"Deleting attribute from {instance}")
        # Here, you can implement deletion logic, e.g., from a dictionary
        if hasattr(instance, '_value'):
            del instance._value

class MyClass:
    attr = Descriptor()

obj = MyClass()
del obj.attr  # calls Descriptor.__delete__(obj)

Thus, __delete__() allows controlling the behavior when an attribute is deleted, such as cleaning up related data or performing additional actions.