Python 3 reference · Built-in Functions
Python setattr() Function
Set an attribute on an object by name, given as a string. setattr(obj, 'x', 5) is the same as obj.x = 5.
Python 3 Since 3.0
Syntax
setattr(object, name, value)
Parameters
| Parameter | Description |
|---|---|
object |
The object to change. |
name |
The attribute name as a string. |
value |
The new value. |
Return value
None.
Examples
class Settings:
pass
s = Settings()
for key, value in {"theme": "dark", "font_size": 14}.items():
setattr(s, key, value)
print(s.theme, s.font_size)
Output
dark 14
class Counter:
hits = 0
setattr(Counter, "hits", Counter.hits + 1)
print(Counter.hits)
Output
1
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
getattr()· Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.hasattr()· Return True if an object has an attribute with the given name. It works by calling getattr() and catching AttributeError.delattr()· Delete a named attribute from an object. delattr(obj, 'name') does the same as del obj.name when the name is in a variable.vars()· Return the __dict__ of a module, class or object: its writable attributes as a dictionary. With no argument, like locals().- Python Classes and Objects · tutorial