setattr(object, name, value)

Adds a specified attribute to an object.

Parameters

  • obj: object The object to which the attribute must be added.
  • name: str A string with the attribute’s name. Specify a new or existing attribute name.
  • value: Any The value of the attribute.

The object’s attribute will be added if the object supports this action. This function is useful when the attribute name or value is stored in a variable and is not known beforehand. To retrieve an attribute, use getattr(). To delete an attribute, use delattr(). To check for an attribute’s existence, use hasattr().

Return Value

  • The setattr() function returns None.

Examples

class Person:
    name = 'Peter'
    
p = Person()
print('Name before:', p.name)

# Set name to 'John'
setattr(p, 'name', 'John')

print('Name after:', p.name)

# Result

Name before: Peter
Name after: John