Intercepting Attributes: __getattr__ vs __getattribute__
`__getattr__` only fires when an attribute is NOT found in `__dict__`. In contrast, `__getattribute__` intercepts EVERY single attribute access unconditionally 🕵️.
class FallbackDict:
def __init__(self):
self.known = "I exist"
def __getattr__(self, name):
# Only called when attribute is missing:
return f"Dynamic fallback for: {name} 🕵️"
fb = FallbackDict()
print(fb.known) # 'I exist' (normal lookup)
print(fb.magic_tool) # 'Dynamic fallback for: magic_tool 🕵️'
# 63. Intercepting Attributes: __getattr__ vs __getattribute__ `__getattr__` only fires when an attribute is NOT found in `__dict__`. In contrast, `__getattribute__` intercepts EVERY single attribute access unconditionally 🕵️. ```python class FallbackDict: def __init__(self): self.known = "I exist" def __getattr__(self, name): # Only called when attribute is missing: return f"Dynamic fallback for: {name} 🕵️" fb = FallbackDict() print(fb.known) # 'I exist' (normal lookup) print(fb.magic_tool) # 'Dynamic fallback for: magic_tool 🕵️' ``` Be careful with `__getattribute__`: accessing `self.anything` inside it triggers infinite recursive recursion unless you call `super().__getattribute__(name)`! 🕵️ --- ### Question When does Python invoke `__getattr__` on an object? 🧠 - [ ] a. Only as a fallback when the attribute is not found by standard lookup 🕵️ - [ ] b. Before checking any instance or class dictionaries - [ ] c. Only when attributes are deleted with del - [ ] d. Every single time an attribute is read --- ### Challenge Write class `Proxy` with `__getattr__(self, name)` returning `f'accessed_{name}'`. Create `p = Proxy()` and print `p.database`. 🎯 <details> <summary>Solution</summary> ```python class Proxy: def __getattr__(self, name): return f"accessed_{name}" p = Proxy() print(p.database) ``` </details>