Junior — Middle
What is the difference between __getattribute__ and __getattr__ methods in Python and how do they work when accessing object attributes?
sobes.tech AI
Answer from AI
The methods __getattribute__ and __getattr__ in Python are used to intercept access to an object's attributes, but they work differently:
-
__getattribute__(self, name)is called for any access to an attribute of the object. It is the most general interceptor, and if overridden, you need to carefully call the base method to avoid recursion. -
__getattr__(self, name)is called only if the attribute namednameis not found in the usual way (i.e., not present in the object's dictionary or in the classes).
Example:
class Example:
def __getattribute__(self, name):
print(f"__getattribute__ called for {name}")
return super().__getattribute__(name)
def __getattr__(self, name):
print(f"__getattr__ called for {name}")
return f"Default value for {name}"
obj = Example()
obj.existing = 42
print(obj.existing) # Calls __getattribute__, returns 42
print(obj.missing) # Calls __getattribute__, then __getattr__, returns a string
Thus, __getattribute__ is a universal interceptor, while __getattr__ is a fallback for missing attributes.