In this lesson, you will learn how to distinguish between accessing a descriptor through an object instance versus through the class itself to control your program's behavior.
The Mechanics of Access
When you access an attribute, Python checks whether that attribute is a descriptor. If you access it via an instance (e.g., obj.attr), Python invokes the __get__ method with instance=obj and owner=type(obj). However, if you access it via the class (e.g., MyClass.attr), Python invokes __get__ with instance=None and owner=MyClass.
This distinction allows you to decide whether your descriptor should return data bound to a specific object or return the descriptor object itself when accessed globally.
Implementation Example
Consider a descriptor that behaves differently based on how it is accessed:
class Descriptor:
def __get__(self, instance, owner):
if instance is None:
# Accessed via Class
return "You are accessing the descriptor through the class."
# Accessed via Instance
return f"Hello, {instance.name}!"
class User:
greet = Descriptor()
def __init__(self, name):
self.name = name
user = User("Alice")
print(user.greet) # Returns: Hello, Alice!
print(User.greet) # Returns: You are accessing the descriptor through the class.
Why This Matters
By checking for instance is None, you can prevent errors that might occur if a descriptor expects data from an object that doesn't exist. For instance, if your descriptor manages private instance state, accessing it through the class might cause an AttributeError or unexpected behavior. Handling the instance is None case allows you to provide a meaningful representation of the descriptor—or even the descriptor instance itself—rather than crashing or returning None. This is commonly used in frameworks where decorators or descriptors need to provide configuration metadata when accessed at the class level, while providing functional results when accessed at the instance level.
Key Takeaway: Use the instance argument in __get__ to differentiate between logic required for a specific object and logic required for the descriptor's class-level definition.