setattr () is used to set an attribute of an object to its value. In addition to the methods of assigning values to class variables using constructors and object functions, this method provides an alternative way of assigning a 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: demonstration of how setattr () works
|
Output:
Before setattr name: Python.Engineering After setattr name: Geeks4Geeks
setattr () properties
- setattr () can be used to assign None to any object attribute.
- setattr () can be used to initialize a new attribute on an object.
Code # 2: demonstrating setattr () properties
|
Output:
Before setattr name: Python.Engineering After setattr name: None After setattr description: CS portal