How to Use the Python setattr() Function

09/17/2021

Contents

In this article, you will learn how to use the Python setattr() function.

Python setattr() Function

The Python setattr() function is used to set the value of an attribute of an object. It takes three arguments: the object whose attribute you want to set, the name of the attribute as a string, and the value you want to set.

Syntax

Here’s the syntax for using setattr():

setattr(object, name, value)
Example
class Person:
    pass

person = Person()
setattr(person, 'name', 'Alice')
print(person.name) # Output: Alice

In this example, we create a Person class with no attributes. Then, we create an instance of the class called person. We use setattr() to set the name attribute of person to ‘Alice’. Finally, we print out the name attribute of person using the dot notation.

We can also use a variable to set the attribute name:

class Person:
    pass

person = Person()
attribute_name = 'name'
setattr(person, attribute_name, 'Alice')
print(person.name) # Output: Alice

In this example, we store the attribute name in a variable called attribute_name and use it as the second argument to setattr().

Note that setattr() only works on objects that allow setting attributes, such as instances of classes or certain built-in objects like dictionaries. Attempting to use setattr() on objects that don’t support it will raise an AttributeError.