Python setattr() Function
Description
setattr() The corresponding function getattr(), used to set the value of an attribute, which does not necessarily already exist.
Syntax
setattr() syntax:
setattr(object, name, value)
Parameters
- object -- the object.
- name -- a string, the attribute name.
- value -- the attribute value.
Return Value
none.
Example
The following examples demonstrate how to use the setattr() function:
Assigning 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 the value:
class
A
(
)
: ...
name
=
"
runoob
"
... >>>
a
=
A
(
)
setattr
(
a
,
"
age
"
,
28
)
(
a
.
age
)
28
Python built-in function