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

ParameterDescription
object The object to change.
name The attribute name as a string.
value The new value.

Return value

None.

Examples

Set attributes from a dictionaryTry it yourself
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
Change a class attributeTry it yourself
class Counter:
    hits = 0

setattr(Counter, "hits", Counter.hits + 1)
print(Counter.hits)

Output

1

Version history

VersionChange
Python 3.0Added