Python Reference Library →

Python setattr() Function – Dynamically Set Object Attributes

Let’s look at setattr() function – dynamically set object attributes

  1. Notice

    setattr() assigns an attribute by its name, when the object allows that assignment.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
class Box:
    pass
box = Box()
setattr(box, "value", 3)
print(box.value)
Live state

Top-level scope

Box→Object 1
box→Object 2
Object 1 · typeclass BoxObject 2 · BoxBox({'value': 3})
This step

setattr() assigns an attribute by its name, when the object allows that assignment.

Picture setattr() function – dynamically set object attributes

setattr() assigns an attribute by its name, when the object allows that assignment.

Image brief

Alt text
A diagram for Python setattr() Function – Dynamically Set Object Attributes. Instructions: class Box: pass box = Box() setattr(box, "value", 3) print(box.value). Displayed result: 3. The final example bindings are Box --> object 1 (type); box --> object 2 (Box). object 1: class Box; object 2: Box({'value': 3})
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python setattr() Function – Dynamically Set Object Attributes". Teaching focus: setattr() assigns an attribute by its name, when the object allows that assignment. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS class Box: pass box = Box() setattr(box, "value", 3) print(box.value) | v DISPLAYED RESULT 3 FINAL BINDINGS Box --> object 1 (type) box --> object 2 (Box) object 1: class Box object 2: Box({'value': 3}) Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python setattr() Function – Dynamically Set Object Attributes. Instructions: class Box: pass box = Box() setattr(box, "value", 3) print(box.value). Displayed result: 3. The final example bindings are Box --> object 1 (type); box --> object 2 (Box). object 1: class Box; object 2: Box({'value': 3})

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
class Box:
    pass
box = Box()
setattr(box, "value", 3)
print(box.value)
Live state

Top-level scope

Box→Object 1
box→Object 2
Object 1 · typeclass BoxObject 2 · BoxBox({'value': 3})
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
3

What do you expect this program to print?

What does this example display?

class Box:
    pass
box = Box()
setattr(box, "value", 3)
print(box.value)
What does this example display?
Choose one answer. You can try again.

Answer and explanation

3

Follow the printed values in order. The output is: 3

More examples and reference

Python setattr() Function

The setattr() function in Python lets you set or update the value of an attribute of an object dynamically. It’s commonly used when you don't know the attribute name in advance and need to assign it programmatically.

Syntax

setattr(object, name, value)

Parameters:

  • object – The object whose attribute is to be set.
  • name – A string, the name of the attribute to set.
  • value – The value to assign to the attribute.

Returns:

  • None. It updates the object in-place.

Example 1: Set an Attribute Dynamically

class Person:
    pass

p = Person()
setattr(p, 'name', 'Alice')
print(p.name)
Alice

Explanation: We dynamically added a name attribute to the Person object using setattr().

Example 2: Update an Existing Attribute

class Car:
    def __init__(self):
        self.color = "Red"

c = Car()
setattr(c, 'color', 'Blue')
print(c.color)
Blue

Explanation: The existing color attribute was updated from "Red" to "Blue".

Use Case: When to Use setattr()

  • When reading attribute names from a configuration file or user input.
  • When dynamically building objects in frameworks, serializers, or parsers.
  • When using loops to apply attributes programmatically.

Example 3: Use in a Loop

class Item:
    pass

item = Item()
attrs = {'name': 'Book', 'price': 250, 'stock': 100}

for key, value in attrs.items():
    setattr(item, key, value)

print(item.name, item.price, item.stock)
Book 250 100

Explanation: Multiple attributes were added dynamically using setattr() inside a loop.

Common Mistakes

  • Passing a non-string as the attribute name will raise a TypeError.
  • Trying to set attributes on built-in types (like int or str) will raise an AttributeError.

Interview Tip

Use setattr() to create flexible classes in object-oriented design. It’s useful in metaprogramming, decorators, and frameworks like Django or Flask.

Summary

  • setattr() dynamically sets or updates an attribute on an object.
  • It requires three arguments: object, attribute name (as a string), and value.
  • Common in dynamic applications like configuration loaders, ORMs, and testing.

Practice Problem

Write a Python class Student and dynamically add name, grade, and subject using setattr(). Then print all three attributes.

class Student:
    pass

s = Student()
setattr(s, 'name', 'Ravi')
setattr(s, 'grade', 'A')
setattr(s, 'subject', 'Math')

print(s.name)
print(s.grade)
print(s.subject)

What to remember

Connect what you noticed in the example with the idea below.

Remember

setattr() assigns an attribute by its name, when the object allows that assignment.

Watch out for this idea

setattr() assigns a key in every dictionary automatically.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →