Python setattr() Function
Python has lots of in-built methods to access, modify and perform other operations on different data types. One of these built-in methods is setattr(). It is used to assign a value to an object. Using this method, we can assign value to a class variable without constructors and object functions.
Below is the syntax of the :
This method returns a value of type None. It is usually used in classes in Python for accessing the class variables and assigning the value. This method can also initialize a new object attribute to the class.
Example of using Python setattr() function
class Language: english="hello" l=Language() setattr(l,"english","Hello") print(l.english)
Code II: (In continuation with Code I)
Below is the output of our program:
Code I: Hello Code II: Namaste
Here, we are using a class with the name Language. The class has an object attribute named english with the value “hello“. To change the value of the object attribute, we used setattr (). The parameters include
- The variable with which we instantiated the class Language is l. So, l is the second parameter.
- It is then used to access the class and set new value to the attribute named english. Thus, “english” is the second parameter
- The value here is changed to “Hello”. Then, “Hello” is the third parameter.
In Code I, we print the value assigned to the object attribute “english”.
In Code II, we have initiated a new attribute “hindi” and assigned the value “Namaste” to it. Then the value to attribute hindi is printed using the initiation variable l in the statement- print(l.hindi).