Python setattr() Function

Sets the attribute of an object. The attribute must have been initialized in the class.


setattr(object, name, value)


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.


class MyObject   
    def __init__(self): 
        self.x = 10

object = MyObject()
setattr(object, 'x', 20)


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.