Python setattr Function with Examples

The Python setattr function serves the purpose of assigning a value to an attribute of an object. This function requires three parameters: the object itself, a string representing the name of the attribute, and an arbitrary value to be assigned. It does not return any value (returns None). This function is particularly useful for adding a new attribute to an object and initializing it with a specified value. Below is the signature of the function.

Python setattr Function Syntax

It has the following syntax:

Example

setattr (object, name, value)

Parameters

  • object : It is an object which allows its attributes to be changed.
  • name : A name of the attribute.
  • value : A value, set to the attribute.

All the parameters are required.

Return

It returns None to the caller function.

Different Examples for Python setattr Function

Let's explore a few instances of the setattr function to grasp its capabilities.

Python setattr Function Example 1

In this section, we are introducing a new attribute and assigning a value to it through the utilization of the setattr function.

Example

class Student:

    id = 0

    name = ""

    def __init__(self, id, name):

        self.id = id

        self.name = name

student = Student(102,"Sohan")

print(student.id)

print(student.name)

#print(student.email) product error

setattr(student, 'email','sohan@abc.com') # adding new attribute

print(student.email)

Output:

Output

102

Sohan[email protected]

Python setattr Function Example 2

In situations where we prefer not to assign any specific value, we can, by default, utilize None.

Example

class Student:

    id = 0

    name = ""

    def __init__(self, id, name):

        self.id = id

        self.name = name

student = Student(102,"Sohan")

print(student.id)

print(student.name)

setattr(student, 'email',None) # adding new attribute having None

print(student.email)

Output:

Output

102

Sohan

None

Python setattr Function Example 3

It is possible to reassign (or reset) the value of an attribute even after utilizing the setattr function. Consider the example provided below.

Example

class Student:

    id = 0

    name = ""

    def __init__(self, id, name):

        self.id = id

        self.name = name

student = Student(102,"Sohan")

print(student.id)

print(student.name)

setattr(student, 'email',None) # adding new attribute having None

student.email = "Tom@abc.com" # Assigning new value

print(student.email)

Output:

Output

102

Sohan[email protected]

Input Required

This code uses input(). Please provide values below: