Python setattr() Function
Description
setattr()function corresponds to functiongetattr(), used to set the attribute value, which does not necessarily exist.
Syntax
setattr() syntax:
setattr(object, name, value)
Parameters
- object -- Object.
- name -- String, object attribute.
- value -- Attribute value.
Return Value
None.
Examples
The following example demonstrates the usage of the setattr() function:
Assign a value to an existing attribute:
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # Get the value of attribute bar
1
>>> setattr(a, 'bar', 5) # Set the value of attribute bar
>>> a.bar
5
If the attribute does not exist, a new object attribute is created and assigned a value:
>>>class A():
... name = "example"
...
>>> a = A()
>>> setattr(a, "age", 28)
>>> print(a.age)
28
>>>
Python Built-in Functions