Skip to main content

Python setattr() Function

The setattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

Syntax

setattr(object, name, value)

setattr() Parameters

Python setattr() function parameters:

ParameterConditionDescription
objectRequiredObject whose attribute has to be set
nameRequiredString that contains the attribute's name
valueRequiredValue given to the attribute

setattr() Return Value

Python setattr() function returns None.

Examples

Example 1: Basic usage of setattr() function to add a new Attribute

For example, consider the Person class defined with an attribute name. Create an instance p of Person and then use setattr() to add a new attribute age with value 25.

class Person:
def __init__(self, name):
self.name = name

p = Person('Tom')
setattr(p, 'age', 25)

print(p.name) # Output: Tom
print(p.age) # Output: 25

output

Tom
25
note

You can add a new attribute and assign a value to it only if the object implements the __dict__() method.

You can check if your class implement __dict__() by using the dir() function in this way:

class Person:
def __init__(self, name):
self.name = name

print(dir(Person))

output

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

Example 2: Modifying an Existing Attribute

setattr() function can be used to modify an existing attribute of an object.

In the following example, the Person instance p has a name attribute set to 'Tom'. setattr() function is then used to change the name attribute to 'Ryan'.

The output shows that the name attribute has been successfully modified.

class Person:
name = 'Tom'

p = Person()
print('Before modification:', p.name)

# Setting name to 'Ryan'
setattr(p, 'name', 'Ryan')

print('After modification:', p.name) # Output: Ryan

output

Before modification: Tom
After modification: Ryan