Skip to main content

setattr()

The setattr() function in Python is a built-in function that sets the attribute of a given object. It takes three arguments: the object, the attribute name as a string, and the attribute value. This function is commonly used to dynamically set attributes on objects at runtime.

Parameter Values

Parameter Description
object

The object whose attribute will be set.

name

A str representing the name of the attribute to be set.

value

The value to set the attribute to.

Return Values

The setattr() function always returns None.

How to Use setattr() in Python

Example 1:

The setattr() function sets the value of the specified attribute of the specified object.

class Person:
    name = 'John'

p = Person()
setattr(p, 'name', 'Alice')
print(p.name) # Output: Alice
Example 2:

The setattr() function can also be used to create new attributes if the specified attribute does not already exist.

class Person:
    pass

p = Person()
setattr(p, 'age', 25)
print(p.age) # Output: 25
Example 3:

You can also use setattr() to set attributes of built-in objects like lists.

my_list = [1, 2, 3]
setattr(my_list, 'name', 'example')
print(my_list.name) # Output: example