Question 29: Understanding Descriptors in Python

Understanding Descriptors in Python: Customizing Attribute Access

In Python, descriptors are used to customize attribute access.

A descriptor is any object that implements one or more of the descriptor methods (__get__, __set__, __delete__).

Question: Understanding Descriptors in Python: Customizing Attribute Access

What will be the output of the following?

class DescriptorExample:
    def __get__(self, instance, owner):
        return 'Descriptor value'

class MyClass:
    attr = DescriptorExample()

obj = MyClass()

print(obj.attr)














Answer: A

The DescriptorExample class defines the __get__ method, which is part of Python’s descriptor protocol.

When you try to access obj.attr, Python calls the __get__ method of the descriptor (because attr is an instance of DescriptorExample), which returns the string 'Descriptor value'.

Leave a Reply