4. Descriptor Protocols
These examples demonstrate how Python's descriptor protocol (__get__, __set__, and __set_name__) allows fine-grained control over attribute access and modification.
class Descriptor:
def __get__(self, instance, owner):
print("Getting value")
return instance._value
def __set__(self, instance, value):
print("Setting value")
instance._value = value
class MyClass:
attribute = Descriptor()
obj = MyClass()
obj.attribute = 42 # Setting value
print(obj.attribute) # Getting value, Output: 42Last updated