Python setattr()

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

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s