search

What is the use of the "setattr" method in Python?

The **setattr** method in Python is used to set the value of an attribute of an object. It takes the object, the name of the attribute, and the value to be assigned as arguments. The following is a simple example of how to use the **setattr** method:

class MyClass:
    def __init__(self):
        self.x = 0

obj = MyClass()

setattr(obj, 'x', 10)

print(obj.x)

This will output **10**, showing that the value of the **x** attribute has been successfully set using the **setattr** method.

Related Questions You Might Be Interested