Python

Python Setattr() Function

We are all aware that an object function and function constructor can be used to refer specifically to a class variable. The setattr() method is the only other alternative to this one. In dynamic programming, where the variable name is not static, the setattr() method is helpful. The dot operator is inapplicable in that situation. Using the user input as an illustration, it sets the value of an object attribute. A value is assigned to an object’s attribute using the setattr() function in Python. It accepts an object, a string, and an unspecified value as parameters but doesn’t provide any output. When we wish to give an object a new attribute and assign a value to it, it is useful.

You will gain knowledge about the setattr() method of Python in this article, while we cover what it accomplishes, when to employ it, and when it is unnecessary. Regardless of whether the attribute is present or not, the method is used to define an attribute’s value for an object.

Syntax of the Setattr() Function in Python

The following is the setattr() syntax that we deployed in a Python script:

setattr(set_object, set_variable, set_value)

 
The object.attribute parameter is set to equal value using the arguments name of the object, variable name, and value. This function does not throw any exceptions because any object property can be of a certain type. It returns Nothing to the calling function.

Example 1: Program of Using the Setattr() Function

The setattr() method shows how the object-oriented programming still works well in these situations and is highly useful if an object’s attributes can change while it is being utilized. Here is the program to demonstrate the working of the setattr() function:

class Employee:
    Emp_name = 'Alice'
my_object = Employee()
print("Before setattr employee name : ", my_object.Emp_name)
setattr(my_object, 'Emp_name', 'Alice jeo')
print("After setattr employee name : ", my_object.Emp_name)

 

In the script, we first established a class that is represented with the name “Employee”. In the specified class, we created a class variable as “Emp_name”. The class variable “Emp_name” is set with the string value that is the name of the employee. Then, we defined an object as “my_object” and invoked the class “Employee”. The print is utilized here to print the value of the variable “Emp_name” before the setattr() function is deployed.

To the setattr function, we passed three inputs: my_obeject, the variable name “Emp_name”, and the modified value of the variable “Emp_name”. Then, in the last print statement, we printed the employee name after using the setattr() function.

The following is the outcome obtained from the previous script of the Python setattr() function:

Example 2: Program of Using the Setattr() Function Property

Here, we showed the property of the setattr() function in Python.

class Animal:
    animal_name = 'Cat'
obj1 = Animal()

print("Before setattr name : ", str(obj1.animal_name))

setattr(obj1, 'animal_name', None)

setattr(obj1, 'detail', 'Persian kittens')

print("After setattr animal name : " + str(obj1.animal_name))
print("After setattr animal detail : ", str(obj1.detail))

 

In the previous script, we defined the class to which we have assigned the name “Animal”. To the class “Animal”. We defined a variable as “animal_name” which is set with the string value of the animal’s name “cat”. Then, we have an object as “obj1” where the class “Animal” is invoked. Then, we printed the object by passing it in the str method before the setattr() function.

After that, the setattr() function is deployed where the “obj1” is passed. The “animal_name” variable is also passed with the value “none”. Here, we deployed another setattr() function to the new attribute and initialized it with the new value. The print statement is provided to print the object after the setattr() function.

The setattr() function results before and after utilizing it are shown in the following:

Example 3: Program of Using the Setattr() Function with Dict

Having the ability to set numerous attributes simultaneously is one benefit of utilizing the setattr() function. If you were given a dictionary of an object’s characteristics, what would it contain? To set them for the various attributes of an object, you can loop over them.

class MyDictClass(object)
    def __init__(self, dict1)
        for key in dict1:
            setattr(self, key, dict1[key])
if __name__ == "__main__":
   
    dict1 = {"Student_Name": "Edison",
            "Student_ID": "3278",
            "Student_Degree": "IT"}
   
    my_result = MyDictClass(dict1)
   
    print("After the conversion of Dictionary to Class : ")
    print(my_result.Student_Name, my_result.Student_ID, my_result.Student_Degree)
    print(type(my_result))

 

In this particular script, we first defined the class “MyDictClass”. We called the object to the class. Then, we have a definition of the init method which takes the “self” and the “dict1” as arguments.

After that, we have the for loop which loops over each key and the value of the given dictionary. We then deployed the setattr() function where the self, key, and dict values are added. Then, within the main function of this script, we created the dictionary. After that, we passed that dictionary to the class “MyDictClass” with the help of the newly created object – “my_result”. In the end, we printed the result.

Example 4: Program of Using Setattr() Function with Exception

Here, we’ll construct the read-only attributes for the object. If we attempt to use the setattr() function to change the attribute’s value, an exception is raised.

class Product:

    def __init__(self):
        self._Function = None

    def Function(self):
        print('Function called')
        return self._Function

    obj = property(Function, None)

p1 = Product()

setattr(p1, 'obj', 'laptop')

 

First, we have the class definition as “Product”. We defined the init method where the self as an argument is provided to the class. The variable is created as a “Function” that has a value set to none. Then, we defined the function of the previous variable, “Function”.

After that, we created an object as “obj” where we have the property name “function”. To the property function, we passed the variable “Function” and its value. The setattr() function is invoked to which we provided the p1, obj, and the new value which throws the exception.

You can see that the following exception is raised from the previous script:

Conclusion

This article taught us how to utilize the setattr() function to dynamically set the object attributes while an application is running. When the properties are unknown to the developer and an API needs to be flexible, this is a highly helpful way for the Object-Oriented Programming. You learned how to assign a value to an object’s attribute using the Python setattr() function. Your knowledge of defining the function with the setattr() function is also cleared. Then, you learned how to use the setattr() method while using it to set the attributes with a Python dictionary.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content