Python setattr(): Dynamically Set an Attribute of an Object

The setattr() function sets (or updates) an attribute of an object dynamically. It’s useful for modifying attributes at runtime, handling dynamic data, and working with reflection (introspection).

Example

class Person:
    pass

p = Person()
setattr(p, "name", "Alice")  # Creates and sets the 'name' attribute
print(p.name)

Output:

Alice

Creates a new attribute dynamically.

Syntax

setattr(object, name, value)
  • object → The object whose attribute to modify.
  • name → The attribute name (string).
  • value → The value to assign to the attribute.
  • ReturnsNone (modifies the object in place).

1. Setting an Attribute Dynamically

class Car:
    pass

c = Car()
setattr(c, "color", "Red")
print(c.color)  # Output: Red

setattr() creates color on the fly.

2. Updating an Existing Attribute

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

p = Person("Alice")
setattr(p, "name", "Bob")
print(p.name)  # Output: Bob

Changes name from “Alice” to “Bob”.

3. Using setattr() with a Loop

class User:
    pass

fields = {"name": "John", "age": 30, "city": "New York"}
user = User()

for key, value in fields.items():
    setattr(user, key, value)

print(user.name, user.age, user.city)  
# Output: John 30 New York

Dynamically adds multiple attributes from a dictionary.

4. Checking Before Setting an Attribute

class Laptop:
    def __init__(self, brand):
        self.brand = brand

l = Laptop("Dell")

if not hasattr(l, "model"):
    setattr(l, "model", "XPS 15")

print(l.model)  # Output: XPS 15

Uses hasattr() to avoid overwriting existing attributes.

5. Using setattr() with getattr()

class Book:
    pass

b = Book()
setattr(b, "title", "Python Basics")

print(getattr(b, "title"))  # Output: Python Basics
  • setattr() sets an attribute.
  • getattr() retrieves it dynamically.

6. Trying to Set a Read-Only Attribute

class Immutable:
    __slots__ = ("name",)  # Only allows 'name' attribute

obj = Immutable()
setattr(obj, "name", "Fixed")  # Works fine
setattr(obj, "age", 25)  # AttributeError: 'Immutable' object has no attribute 'age'

__slots__ restricts allowed attributes, preventing unexpected changes.

Key Notes

  • Dynamically sets (or updates) attributes.
  • Creates new attributes if they don’t exist.
  • Useful for handling dynamic objects and dictionaries.
  • Pairs well with getattr() and hasattr().

By using setattr(), you can modify objects dynamically, manage data efficiently, and build flexible programs. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top