How to use setattr() in Python

setattr() in Python is a method that assigns a value to the attribute of an object.

Apart from assigning a value, it also has the following properties.

  1. It can be used to assign None to an object attribute.
  2. It can be used to initialize a new object attribute.

Syntax

setattr(obj, var, val)

Parameters

setattr() has the following parameters.

  1. obj: object whose attribute has to be set.
  2. var: name of the attribute to be set.
  3. val: value given to the attribute.

Return value

setattr() returns None.

Example code 1: Simple

# creating a class
class sampleClass:
number = "5"
# creating an object of that class
obj = sampleClass()
# Before modification
print("Before modification:", obj.number)
# using setattr() to assign a new value
setattr(obj, "number", "10")
# After modification
print("After modification:", obj.number)

Example code 2: Properties of setattr()

# creating a class
class sampleClass:
number = "5"
# creating an object of that class
obj = sampleClass()
# Before modification
print("Before modifying 'number':", obj.number)
# using setattr() to assign None to existing attribute
setattr(obj, "number", None)
# using setattr() to create a new attribute
setattr(obj, "name", "Edpresso")
# After modification
print("After modifying 'number':", obj.number)
print("After creating 'name':", obj.name)

Free Resources