Python setattr() Function



The Python setattr() function is a built-in function that allows us to set a new value to an attribute of the specified object. It is used for creating a new attribute and setting values to it.

In the next few sections, we will be learning more about this function.

Syntax

Following is the syntax of the Python setattr() function −

setattr(object, attribute, value)

Parameters

The Python setattr() function accepts the following parameters −

  • object − This parameter represents an object.

  • attribute − It represents the attribute name.

  • value − It specifies the value to be set.

Return Value

The Python setattr() function returns None value.

Examples

In this section, we will see some examples of setattr() function −

Example 1

The following example shows the usage of Python setattr() function. Here, we are creating a class and setting a new attribute of that class.

class OrgName:
   def __init__(self, name):
      self.name = name

nameObj = OrgName("TutorialsPoint")
setattr(nameObj, "location", "Hyderabad")  
print("Location is set to:", nameObj.location) 

When we run above program, it produces following result −

Location is set to: Hyderabad

Example 2

The setattr() function can also be used to modify the value of existing attributes. In the code below, we are modifying the previously set value of the location attribute with the new one using setattr() function.

class TutorialsPoint:
   def __init__(self, location):
      self.location = location

locationObj = TutorialsPoint("Hyderabad")
print("Before modifying location is set to:", locationObj.location) 
setattr(locationObj, "location", "Noida")  
print("After modifying location is set to:", locationObj.location)

Following is an output of the above code −

Before modifying location is set to: Hyderabad
After modifying location is set to: Noida

Example 3

With the help of setattr() function, we can add methods to classes dynamically. In the following code, we have defined a method named "employee" and by using the setattr() function, we are adding the defined method to the specified class.

class TutorialsPoint:
   pass
    
def employee():
   return "Present"

employeeObj = TutorialsPoint()
setattr(employeeObj, "isPresent", employee)  
print("Status of employee is set to:", employeeObj.isPresent())

Output of the above code is as follows −

Status of employee is set to: Present
python_built_in_functions.htm
Advertisements