setattr() function is a built-in Python function used to set the value of a named attribute of an object. It allows a developer to dynamically assign or modify attributes of an object at runtime.
setattr(object, attribute, value)
setattr() function requires three parameters:
object: an object.
attribute: name of the attribute to be set.
value: the value to give the
The following example will change the value of the
name attribute of the
class Person:name = "Alex"age = 30# Updating the name propertysetattr(Person, "name", "John")# Retrieving the name propertynew_name = getattr(Person, "name")print("My new name is " + new_name)
The code results in the following output:
My new name is John
Suppose there is a
Person class that represents a person with attributes such as name and age. The
setattr() function can be used to dynamically set the value of an attribute.
- Anonymous contributorAnonymous contributor1 total contribution
- Anonymous contributor