Yandex

Python setattr() Function – Dynamically Set Object Attributes



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)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M