Python setattr()

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

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

The syntax of setattr() method is:

setattr(object, name, value)

If you want to get an attribute of an object, use getattr().

setattr() Parameters

The setattr() method takes three parameters:

  • object - object whose attribute has to be set
  • name - string which contains the name of the attribute to be set
  • value - value of the attribute to be set

Return value from setattr()

The setattr() method returns None.

Example 1: How setattr() works in Python?

class Person:

    name = 'Adam'

p = Person()

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

# setting name to 'John'

setattr(p, 'name', 'John')

print('After modification:', p.name)

When you run the program, the output will be:

Before modification: Adam

After modification: John

Example 2: setattr() when named attribute is not found and setting attribute to None

If the attribute is not found, setattr() creates a new attribute by the given name and value.

However, this is only possible if the object implements __dict__() method.

You can check if it does by using dir() method.

class Person:

    name = 'Adam'

p = Person()

# setting attribute name to None

setattr(p, 'name', None)

print('Name is:', p.name)

# setting an attribute not present

# in Person

setattr(p, 'age', 23)

print('Age is:', p.age)

When you run the program, the output will be:

Name is: None

Age is: 23

Add comment

CommentList

The file '/Custom/Widgets/ScriptInjection/widget.cshtml' does not exist.