Junior — Middle
Can you explain the purpose of the __get__() method in Python descriptors and how it is used?
sobes.tech AI
Answer from AI
The __get__() method in Python is part of the descriptor protocol. A descriptor is an object that manages access to attributes of another object.
When an object has a descriptor attribute with a __get__() method, this method is called when accessing that attribute.
Method signature:
def __get__(self, instance, owner):
...
self— the descriptor itselfinstance— the object requesting the attribute (or None if accessed through the class)owner— the class to which the object belongs
Example usage:
class Descriptor:
def __get__(self, instance, owner):
print(f'__get__ called for {instance} of class {owner}')
return 42
class MyClass:
attr = Descriptor()
obj = MyClass()
print(obj.attr) # Accessing attr calls Descriptor.__get__
Output:
__get__ called for <__main__.MyClass object at 0x...> of class <class '__main__.MyClass'>
42
Thus, __get__() allows controlling what is returned when accessing an attribute, enabling properties, computed values, lazy loading, and other patterns.