What does setattr() function do in Python?



The setattr() method

The setattr() method sets the value of given attribute of an object.

Syntax

The syntax of setattr() method is −

setattr(object, name, value)

The setattr() method takes three parameters −

The setattr() method returns None.

Example

class Male:
    name = 'Abel'
x = Male()
print('Before modification:', x.name)
# setting name to 'Jason'
setattr(x, 'name', 'Jason')
print('After modification:', x.name)

Output

This gives the output

('Before modification:', 'Abel')
('After modification:', 'Jason')


Advertisements