How does setattr() work?

QuestionsQuestions8 SkillsProPython Built-in FunctionsNov, 22 2025
0113

The setattr() function in Python is used to set an attribute on an object. It takes three arguments:

  1. Object: The instance of the class on which you want to set the attribute.
  2. Attribute Name: A string representing the name of the attribute you want to set.
  3. Value: The value you want to assign to the attribute.

Syntax

setattr(object, attribute_name, value)

How It Works

  • If the specified attribute already exists on the object, setattr() updates its value.
  • If the attribute does not exist, setattr() creates a new attribute with the specified name and assigns it the given value.

Example

Here's a simple example to illustrate how setattr() works:

class Person:
    def __init__(self, name):
        self.name = name

# Create an instance of Person
p = Person("Alice")

# Set a new attribute 'age' using setattr
setattr(p, 'age', 30)

# Check the attributes
print(p.name)  # Output: Alice
print(p.age)   # Output: 30

In this example:

  • We create a Person object p with a name attribute.
  • We use setattr() to add an age attribute to p.
  • Finally, we print both attributes to confirm that setattr() worked as expected.

If you have any more questions or need further clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!