Python | setattr() method
setattr() 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
Code #1 : demonstrating working of setattr()
# 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
- setattr() can be used to assign None to any object attribute.
- setattr() can be used to initialize a new object attribute.
Code #2 : demonstrating properties of setattr()
# 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
Recommended Posts:
- class method vs static method in Python
- Python | next() method
- Python | os.dup() method
- Python | set() method
- Python | os.write() method
- Python | PyTorch tan() method
- Python | os.read() method
- Python | os.statvfs() method
- Python PIL | getcolors() Method
- Python PIL | putdata() method
- Python | PyTorch cos() method
- Python | os.chmod method
- Python | os.fchdir() method
- Python | os.dup2() method
- Python | os.close() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



