Python Practice › OOP Programs › Program 23

setattr() and getattr()

EasyOOP Programs · 23 of 48

Write a Python program that uses setattr() and getattr().

Advertisement
Output
chromium 30
0

Approach

  1. Set and read attributes whose names are stored in strings.

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment