Python setattr() Function
The Python setattr() function 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. It is one of the built-in functions and does not require any module to use this.
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.
setattr() Function Examples
Practice the following examples to understand the use of setattr() function in Python:
Example: Use of setattr() Function
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: Modify Attribute's Value Using setattr() Function
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.
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: Add Class Methods Dynamically Using setattr() Function
With the help of setattr() function, we can add class methods dynamically. In the following code, we have defined a method named "employee" and 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