setattr() Function in Python

Python setattr() Function

The setattr() function in Python is used to set the value of an attribute of an object. It allows you to dynamically assign or modify an attribute, whether it already exists or not, during runtime. The setattr() function takes three arguments:

  • object: The object on which you want to set the attribute.
  • name: A string representing the name of the attribute you want to set.
  • value: The value you want to assign to the attribute.

The syntax of the setattr() function is as follows:

setattr(object, name, value)

Here's an example of how to use setattr():

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

# Create an instance of MyClass
obj = MyClass()

# Using setattr() to dynamically set 'my_attribute' to a new value
setattr(obj, 'my_attribute', 42)

# Accessing the attribute to verify the change
print(obj.my_attribute)  # Output: 42

# Using setattr() to create a new attribute 'new_attribute' and set its value
setattr(obj, 'new_attribute', 'Hello, World!')

# Accessing the newly created attribute
print(obj.new_attribute)  # Output: Hello, World!

As shown in the example, setattr() can be used not only to modify existing attributes but also to create new attributes on-the-fly.

It's important to note that using setattr() to dynamically create or modify attributes should be done with caution, as it may lead to unexpected behavior or make your code harder to maintain. Generally, it's better to define attributes explicitly in the class definition whenever possible.