Python Func Setattr
# Python2.x Python setattr() Function
[ Python Built-in Functions](#)
* * *
## Description
The **setattr()** function corresponds to the [getattr()](#) function and is used to set attribute values. The attribute does not necessarily have to exist.
## Syntax
setattr() syntax:
setattr(object, name, value)
## Parameters
* object -- Object.
* name -- String, the object attribute.
* value -- Attribute value.
## Return Value
None.
## Example
The following example demonstrates the usage of the setattr() function:
Assigning a value to an existing attribute:
>>>class A(object): ... bar = 1 ... >>>a = A()>>>getattr(a, 'bar')# Get attribute bar value 1>>>setattr(a, 'bar', 5)# Set attribute bar value>>>a.bar 5
If the attribute does not exist, a new object attribute will be created and assigned a value:
>>>class A(): ... name = "tutorial" ... >>>a = A()>>>setattr(a, "age", 28)>>>print(a.age)28>>>
[ Python Built-in Functions](#)
YouTip