Python with setattr() Function

Learn Python @

In Python, the setattr() function serves as a powerful tool for dynamically assigning attributes to objects. This article aims to elucidate its usage, applications, and significance through comprehensive examples.

Understanding setattr() Function

The setattr() function in Python is utilized to dynamically set attributes on objects. Its syntax is as follows:

setattr(object, name, value)

Here, object represents the target object on which the attribute is to be set, name denotes the name of the attribute, and value represents the value to be assigned to the attribute.

Example 1: Dynamic Attribute Assignment

class Person:
p = Person()
setattr(p, 'name', 'Sachin')

Output 1:

Name: <code class="language-python">Sachin 

Example 2: Setting Attributes on Built-in Objects

my_dict = {}
setattr(my_dict, 'key', 'value')
print("Dictionary:", my_dict)

Output 2:

Dictionary: {'key': 'value'}

Example 3: Using setattr() with Dynamic Attribute Names

class Student:
s = Student()
attribute_name = 'age'
attribute_value = 20
setattr(s, attribute_name, attribute_value)
print("Student's Age:", getattr(s, attribute_name))

Output 3:

Student's Age: 20

Points to Remember

  • The setattr() function dynamically sets attributes on objects in Python.
  • It allows for the dynamic assignment of attribute names and values, enhancing the flexibility and dynamism of Python programs.
  • setattr() is particularly useful when dealing with dynamically generated data or when attributes need to be set programmatically.
Author: user