Python setattr() Function
Sets the attribute of an object. The attribute must have been initialized in the class.
Syntax
Python
Copy Code
setattr(object, name, value)
Parameters
Parameter | Description |
---|---|
object |
Required. The object for which the attribute will be set. This can be any type. |
name |
Required. The name of the attribute as a string value. |
value |
Required. The value to set. This can be any type. |
Example
Python
Copy Code
class MyObject def __init__(self): self.x = 10 object = MyObject() setattr(object, 'x', 20)
Notes
While normally one just assigns a value to an attribute, for example
object.x = 10
. In meta-programming, however, it can is often useful to be able to
set an attribute by its name. This technique can be used, for example, to map JSON data or
records from a database to a Python object.
There are many Python libraries that do this already, so there is no reason to write your own unless you have some custom requirements.