Junior — Middle
How do the methods __getattr__ and __getattribute__ affect access to object attributes in Python?
sobes.tech AI
Answer from AI
In Python, the methods __getattr__ and __getattribute__ are used to intercept access to object attributes, but they work differently.
-
__getattribute__(self, name)is called always when attempting to access any attribute of an object. This is the most general access interceptor. If you do not call the base method within it (for example,super().__getattribute__(name)), you can easily create an infinite recursion. -
__getattr__(self, name)is called only if the attribute namednameis not found by the usual means (i.e., it is absent from__dict__and the classes).
Example:
class A:
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 = A()
obj.existing = 42
print(obj.existing) # __getattribute__ is called, returns 42
print(obj.missing) # __getattribute__ is called, not found, then __getattr__ is called
Thus, __getattribute__ allows controlling all attribute access, while __getattr__ only handles cases of missing attributes.