Python setattr() Method

The setattr() function assigns the specified value argument to the specified attribute name (existing or new) of the specified object. This is the counterpart of getattr() method.

The setattr() method is equivalent to object.attribute = value.

Syntax:

setattr(object, name, value)

parameters:

  1. object: The object whose attribute needs to be set.
  2. name: The name of attribute as string.
  3. value: The value to be set.

Return Value:

None.

The following example sets values for various attributes of an object.

Example: setattr()
class student:
    firstName = 'James'
    lastName = 'Bond'

std = student()
print('First Name: ', std.firstName)
print('Last Name: ', std.lastName)

setattr(std,'firstName','Bill')
setattr(std,'lastName','Gates')

print('After setting attributes')

print('First Name: ', std.firstName)
print('Last Name: ', std.lastName)
Output
First Name: James
Last Name:  Bond
After setting attributes
First Name: Bill
Last Name:  Gates

If the specified attribute does not exist in the class, the setattr() creates a new attribute to an object or class and assigns the specified value to it. The following assigns a new attribute to the class itself.

Example: setattr()
class student:
    firstName = 'James'
    lastName = 'Bond'

setattr(student, 'age', 25)
print('After setting attributes')
print('student.age = ', student.age)

s = student()
print('s.age = ', s.age)
Output
student.age = 25
s.age = 25

Note that this new attribute can only be attached to the specified object. The new attribute will not be available to new objects. Use the hasattr method before setting attribute value to avoid error.

Use the . operator instead of the setattr() method to assign the value.

Example: The . Operator
class student:
    firstName = 'James'
    lastName = 'Bond'

student.age = 25 # creates a new attribute

s1 = student()
print('s1.age = ', s1.age) 
s1.firstName = 'Steve' # assigns value to existing attribute
s1.lastName = 'Jobs' # assigns value to existing attribute

s2 = student()
print('s2.age = ', s2.age) 
Output
s1.age = 25
s2.age = 25
Want to check how much you know Python?