English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The setattr() function sets the value of the object's attribute.
The syntax of setattr() function is:
setattr(object, name, value)
If you want to get the attribute of an object, please usegetattr().
The setattr() function has three parameters:
object -The object that must be set for the attribute
name -Attribute name
value -The value assigned to the attribute
The setattr() method does not return anything. It returns None.
class Person: name = 'Adam' p = Person() print('Before modification:', p.name) # Set the name to 'John' setattr(p, 'name', 'John') print('After modification:', p.name)
Output result
Before modification: Adam After modification: John
If the attribute is not found, setattr() creates a new attribute and assigns a value to it. However, this can only be done if the object implements the __dict__() method.
You can usedir()The function checks all properties of the object.
class Person: name = 'Adam' p = Person() # Set the attribute name to John setattr(p, 'name', 'John') print('Name is:', p.name) # Set an attribute that does not exist in Person setattr(p, 'age', 23) print('Age is:', p.age)
Output result
Name is: John Age is: 23