Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python setattr() method

  • Difficulty Level : Easy
  • Last Updated : 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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 

Example 1: Demonstrating the working of setattr()

Python3




# Python code to demonstrate
# working of setattr()
 
# initializing class
class Gfg:
    name = 'GeeksforGeeks'
 
 
# initializing object
obj = Gfg()
 
# printing object before setattr
print("Before setattr name : ", obj.name)
 
# using setattr to change name
setattr(obj, 'name', 'Geeks4Geeks')
 
# printing object after setattr
print("After setattr name : ", obj.name)

Output: 

Before setattr name : GeeksforGeeks
After setattr name : Geeks4Geeks

Python setattr() property

  • setattr() can be used to assign None to any object attribute.
  • setattr() can be used to initialize a new object attribute.

Example 2: Demonstrating properties of setattr() 

Python3




# Python code to demonstrate
# properties of setattr()
 
# initializing class
class Gfg:
    name = 'GeeksforGeeks'
 
 
# initializing object
obj = Gfg()
 
# printing object before setattr
print("Before setattr name : ", str(obj.name))
 
# using setattr to assign None to name
setattr(obj, 'name', None)
 
# using setattr to initialize new attribute
setattr(obj, 'description', 'CS portal')
 
# printing object after setattr
print("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

Example 3: Python setattr() dict

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 class
class Dict2Class(object):
     
    def __init__(self, my_dict):
         
        for key in my_dict:
            setattr(self, key, my_dict[key])
 
# Driver Code
if __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'>

Python setattr() exception

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!