Python setattr() function
Set an attribute by its name as a string.
Syntax
setattr(obj, name, value)
The same as obj.name = value, but the name can come from a variable.
Parameters
| obj | the object |
| name | the attribute name |
| value | the new value |
Return value
None
Example
Code
class Settings: pass s = Settings() for key, value in {"theme": "dark", "size": 14}.items(): setattr(s, key, value) print(s.theme, s.size)
Output
dark 14
Related
Learn it step by step in the free lesson Classes & Objects, with exercises that check your answers.