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

Similar Reads

Python setattr() Function Syntax

...

Python setattr() Examples

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

How setattr() works in Python?...