Python setattr()

In this post, we will see about Python setattr() method.It is just opposite of getattr()
Python setattr() method sets passed value of named attribute of the object. If named attribute is already present, it updates the attribute. If named attribute is not present then it creates a new attribute.


Syntax

As you can see it takes three arguments
object: It is the object whose named attribute value you want to get
name: It is the name of attribute
value: It is value you want to set for above attribute.
this is simply equal to


Return

It returns nothing


Example

Let’s see a very simple example:

class Person: name = 'John' age=29 person = Person() print('The Person name is:', getattr(person, "name")) print('The age of person is:', getattr(person, "age")) setattr(person,'age',30) print('The updated age of person is:', getattr(person, "age"))

Output:

The Person name is: John
The age of person is: 29
The updated age of person is: 30

Let’s understand what happens if attribute is not present in the object

class Person: name = 'John' age=29 person = Person() print('The Person name is:', getattr(person, "name")) print('The age of person is:', getattr(person, "age")) setattr(person,'city','Pune') print('The city of person is:', getattr(person, 'city'))

Output:

The Person name is: John
The age of person is: 29
The city of person is: Pune

As you can see, city attribute does not exist in the class person but setattr method created an attribute city and updated the value to ‘Pune’

That’s all about Python setattr() function.

Leave a Reply

Your email address will not be published. Required fields are marked *