Friday, November 15, 2024
Google search engine
HomeLanguagesPython setattr() method

Python setattr() method

Python setattr() method is used to assign the object attribute its value. The setattr() can also be used to initialize a new object attribute. Also, setattr() can be used to assign None to any object attribute.

Example :

Python3




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


Output :

name: kiran

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() Examples

How setattr() works in Python?

In the given example, we have defined a animal class with a class variable name and we are showing how can we set the value of the variable with setattr().

Python3




class Animal:
    name = 'lucky'
     
p = Animal()
print('Before modification:', p.name)
setattr(p, 'name', 'Woozoo')
 
print('After modification:', p.name)


Output :

Before modification: lucky
After modification: Woozoo

When the attribute is not found in setattr() in Python

In this example, we have defined a Gfg class and we have set the name and descr variables to None after that we have set the variable with setattr() and printed it. After that, we created a variable named a value that was not found in the class with setattr() and printing it in Python.

Python3




class Gfg:
    name = None
    descr = None
 
 
# initializing object
gfg = Gfg()
 
print("Before using setattr:\n"
      f"\tname: {gfg.name}\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: {gfg.name}\n"
      f"\tdescr: {gfg.descr}")
 
# creating new attribute using setattr
setattr(gfg, 'value', 5)
print(f"\nNew attribute created, gfg.value: {gfg.value}")


Output : 

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

New attribute created, gfg.value: 5

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.

Python3




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 using property() function in Python 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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments