Skip to content
Related Articles
Open in App
Not now

Related Articles

Python setattr() method

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 03 Aug, 2022
Improve Article
Save Article
Like Article

Python setattr() method is used to assign the object attribute its value. 

Python setattr() Function Syntax

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

Python setattr() Function Example


class Person:
    def __init__(self):
p = Person()
setattr(p, 'name', 'kiran')
print(f"name: {}")


name: kiran

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 1: Demonstrating properties of setattr()

Using setattr() we can create or update attributes of a class.


class Gfg:
    name = None
    descr = None
# initializing object
gfg = Gfg()
print("Before using setattr:\n"
      f"\tname: {}\n"
      f"\tdescr: {gfg.descr}")
# setting value using setattr
setattr(gfg, "name", "GeeksForGeeks")
setattr(gfg, "descr", "CS Portal")
print("After using setattr:\n"
      f"\tname: {}\n"
      f"\tdescr: {gfg.descr}")
# creating new attribute using setattr
setattr(gfg, 'value', 5)
print(f"\nNew attribute created, gfg.value: {gfg.value}")


Before using setattr:
    name: None
    descr: None
After using setattr:
    name: GeeksForGeeks
    descr: CS Portal

New attribute created, gfg.value: 5

Example 2: Python setattr() dict

Here we are creating attributes of the class ‘Dict2Class’ dynamically using setattr() function by passing a dictionary with some keys and values to the __init__() method of the 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)


After Converting Dictionary to Class : 
Geeks 1223 Python
<class '__main__.Dict2Class'>

Python setattr() exception

Here we will create read-only attributes of the object using property() function in Python and if we try to set the attribute’s value using setattr() function then an exception will rise.


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')


---> 16 setattr(p, 'n', 'rajav')

AttributeError: can't set attribute

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!