Python setattr() method - GeeksforGeeks

30 Sep, 2021
Python setattr() method is used to assign the object attribute its value. 
Apart from ways to assign values to class variables, through constructors and object functions, this method gives you an alternative way to assign value.
Syntax : setattr(obj, var, val)
Parameters : 
obj : Object whose which attribute is to be assigned.
var : object attribute which has to be assigned.
val : value with which variable is to be assigned.
Returns : None 
Python3
# Python code to demonstrate# working of setattr() # initializing classclass Gfg:    name = 'GeeksforGeeks'  # initializing objectobj = Gfg() # printing object before setattrprint("Before setattr name : ", obj.name) # using setattr to change namesetattr(obj, 'name', 'Geeks4Geeks') # printing object after setattrprint("After setattr name : ", obj.name)
Output: 
Before setattr name : GeeksforGeeks
After setattr name : Geeks4Geeks
setattr() can be used to assign None to any object attribute.
setattr() can be used to initialize a new object attribute.
Python3
# Python code to demonstrate# properties of setattr() # initializing classclass Gfg:    name = 'GeeksforGeeks'  # initializing objectobj = Gfg() # printing object before setattrprint("Before setattr name : ", str(obj.name)) # using setattr to assign None to namesetattr(obj, 'name', None) # using setattr to initialize new attributesetattr(obj, 'description', 'CS portal') # printing object after setattrprint("After setattr name : " + str(obj.name))print("After setattr description : ", str(obj.description))
Output: 
Before setattr name : GeeksforGeeks
After setattr name : None
After setattr description : CS portal
Let’s take a simple dictionary “my_dict” which has the Name, Rank, and Subject as my Keys and they have the corresponding values as Geeks, 1223, Python. We are calling a function here Dict2Class which takes our dictionary as an input and converts it to class. We then loop over our dictionary by using setattr() function to add each of the keys as attributes to the class.
Python3
# Turns a dictionary into a classclass Dict2Class(object):         def __init__(self, my_dict):                 for key in my_dict:            setattr(self, key, my_dict[key]) # Driver Codeif __name__ == "__main__":         # Creating the dictionary    my_dict = {"Name": "Geeks",            "Rank": "1223",            "Subject": "Python"}         result = Dict2Class(my_dict)         # printing the result    print("After Converting Dictionary to Class : ")    print(result.Name, result.Rank, result.Subject)    print(type(result))
Output:
After Converting Dictionary to Class : 
Geeks 1223 Python
<class '__main__.Dict2Class'>
Here we will create read-only attributes of the object and if we try to set the attribute’s value using setattr() function then an exception will rise.
Python3
class Person:     def __init__(self):        self._name = None     def name(self):        print('name function called')        return self._name     # for read-only attribute    n = property(name, None) p = Person() setattr(p, 'n', 'rajav')
Output:
---> 16 setattr(p, 'n', 'rajav')

AttributeError: can't set attribute
kumar_satyam
Python-Built-in-functions
python-object
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?