We all know that we can assign a value to a class variable through a constructor and object function. But apart from this, there is one alternate method: the setattr() method.
Python setattr()
Python setattr() is a built-in method that sets the value of a given attribute of an object of a class. The setattr() can assign None to any object attribute and can be used to initialize a new object attribute.
Syntax
See the following syntax.
setattr(object, name, value)
Arguments
The function uses the following three parameters.
object: Object is that whose attribute is to be set or changed.
name: Name is a string that contains the name of the attribute to be set.
value: Value is a value that is to be set.
Return value
The function does not return anything. Therefore, the return value is None.
Program to show how setattr() works
See the following code.
# app.py # Creating a class of name Student class Student: # Creating class attributes name = "Debasis" roll = 24 # creating class object std = Student() # Printing data before using setattr() print("Name is : ", std.name) print("Roll no is: ", std.roll) # Now we will modify student's roll no setattr(std, 'roll', 20) # Printing data after modification print("\nAfter modification: ") print("Name is : ", std.name) print("Roll no is: ", std.roll)
Output
➜ pyt python3 app.py Name is : Debasis Roll no is: 24 After modification: Name is : Debasis Roll no is: 20 ➜ pyt
In the above example, we can see that we have changed the value of roll number from 24 to 20 using the setattr() method, and after that, when we call it, we can see the changed value.
When name attribute is not found and setting attribute to None
See the following code.
# app.py # Creating a class of name Student class Student: # Creating class attributes name = "Debasis" roll = 24 # creating class object std = Student() # Printing data before using setattr() print("Name is : ", std.name) print("Roll no is: ", std.roll) # Here we will set name to None setattr(std, 'name', None) # Now we will set value to an attribute # Which is not present in class setattr(std, 'section', 'CSE171') # Printing data after modification print("\nAfter modification:") print("Name is : ", std.name) print("Roll no is: ", std.roll) print("Section is : ", std.section)
Output
➜ pyt python3 app.py Name is : Debasis Roll no is: 24 After modification: Name is : None Roll no is: 24 Section is : CSE171 ➜ pyt
In the above example, we have set the value of the name attribute to None, so we can learn that we can assign None value also.
On the other hand, as we can see, there is no section attribute in the Student class, but we have used it in setattr().
So what happened, in this case, is, setattr() itself creates a new attribute if that attribute is not present in the class, and then it assigns a given value to it.
Python setattr() with user input
We use the Python input() function to get the input from the user and pass that value to the setattr() function.
See the following code.
# app.py class Student: pass stud = Student() attr_name = input('Enter the attribute name:\n') attr_value = input('Enter the attribute value:\n') setattr(stud, attr_name, attr_value) print('Data attribute =', attr_name, 'and its value =', getattr(stud, attr_name))
Output
➜ pyt python3 app.py Enter the attribute name: character_name Enter the attribute value: Eleven Data attribute = character_name and its value = Eleven ➜ pyt
Python setattr() exception
We can create a read-only attribute using a property function or property decorator in the object.
In that case, if we try to set the attribute value using the setattr() function, we will get AttributeError: can’t set attribute exception.
See the following code.
# app.py class Student: def __init__(self): self._name = None def get_name(self): print('get_name called') return self._name # for read-only attribute name = property(get_name, None) stud = Student() setattr(stud, 'name', 'Krunal')
Output
➜ pyt python3 app.py Traceback (most recent call last): File "app.py", line 16, in <module> setattr(stud, 'name', 'Krunal') AttributeError: can't set attribute ➜ pyt
That’s it for this tutorial.