Dynamic Attribute Access: getattr and setattr
`getattr()`, `setattr()`, and `hasattr()` let you inspect and modify object attributes dynamically using string names at runtime 🔍.
class Config:
timeout = 30
cfg = Config()
# Dynamic write:
setattr(cfg, "retries", 3)
# Dynamic read with safe default fallback:
print(getattr(cfg, "retries")) # 3 🔍
print(getattr(cfg, "host", "127.0.0.1")) # '127.0.0.1' 🛡️
print(hasattr(cfg, "retries")) # True ✅
# 62. Dynamic Attribute Access: getattr and setattr `getattr()`, `setattr()`, and `hasattr()` let you inspect and modify object attributes dynamically using string names at runtime 🔍. ```python class Config: timeout = 30 cfg = Config() # Dynamic write: setattr(cfg, "retries", 3) # Dynamic read with safe default fallback: print(getattr(cfg, "retries")) # 3 🔍 print(getattr(cfg, "host", "127.0.0.1")) # '127.0.0.1' 🛡️ print(hasattr(cfg, "retries")) # True ✅ ``` Providing a third argument to `getattr(obj, name, default)` prevents `AttributeError` when an attribute might not exist! 🔍 --- ### Question What does `getattr(obj, 'missing_field', 42)` return if `missing_field` does not exist on `obj`? 🧠 - [ ] a. 42 (the specified default fallback) 🛡️ - [ ] b. Raises an unhandled AttributeError - [ ] c. None - [ ] d. Creates an empty method with that name --- ### Challenge Create class `Box: pass`. Instantiate `b = Box()`. Use `setattr` to set attribute `'weight'` to `50`. Print `getattr(b, 'weight')`. 🎯 <details> <summary>Solution</summary> ```python class Box: pass b = Box() setattr(b, "weight", 50) print(getattr(b, "weight")) ``` </details>