setattr()

The built-in setattr() function allows you to set the value of an attribute of an object dynamically at runtime using the attribute’s name as a string. This is particularly useful when you don’t know the attribute names in advance:

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

>>> jane = Person("Jane", 25)
>>> setattr(jane, "age", 26)
>>> jane.age
26

setattr() Signature

Python Syntax
setattr(object, name, value)

Arguments

Argument Description
object The object whose attribute you want to set.
name A string representing the name of the attribute to set.
value The new value you want to assign to the specified attribute.

Return Value

  • The setattr() function doen’t return a fruitful value. Instead, it modifies the input object by setting the specified attribute to the given value.

setattr() Examples

With a class instance as an argument:

Python
>>> class Car:
...     def __init__(self, make, model):
...         self.make = make
...         self.model = model
...

>>> toyota = Car("Toyota", "Corolla")
>>> setattr(toyota, "year", 2020)
>>> toyota.year
2020

setattr() Common Use Cases

The most common use cases for setattr() include:

  • Dynamically setting attributes when the attribute names are determined at runtime
  • Modifying attributes of objects in a generic way, such as within a loop
  • Implementing frameworks or libraries that require flexible attribute management

setattr() Real-World Example

Suppose you have a scenario where you need to update multiple attributes of an object based on a dictionary of key-value pairs. You can use setattr() to achieve this dynamically.

Python
>>> class Book:
...     def __init__(self, title, author, year):
...         self.title = title
...         self.author = author
...         self.year = year
...

>>> book = Book("1984", "George Orwell", 1949)
>>> updates = {"title": "Animal Farm", "year": 1945}
>>> for attr, value in updates.items():
...     setattr(book, attr, value)
...
>>> book.title
'Animal Farm'
>>> book.year
1945

In this example, setattr() helps update the book object’s attributes based on the provided dictionary, allowing for flexible and dynamic attribute management.

Related Resources

Tutorial

Python's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 12, 2024 • Reviewed by Dan Bader