Python Practice › OOP Programs › Program 23
setattr() and getattr()
Write a Python program that uses setattr() and getattr().
Output
chromium 30 0
Approach
- Set and read attributes whose names are stored in strings.
Solution
class Config: pass cfg = Config()settings = {"browser": "chromium", "headless": True, "timeout": 30}for key, value in settings.items(): setattr(cfg, key, value) print(cfg.browser, getattr(cfg, "timeout"))print(getattr(cfg, "retries", 0))Output
chromium 30 0
Line by line
Lines 6-7
setattr creates attributes from dictionary keys.
Line 10
getattr with a default does not fail for missing attributes.
Learn the concept
New to this topic? Read the lesson, then come back.