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:
>>> class Person:
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
>>> jane = Person("Jane", 25)
>>> setattr(jane, "age", 26)
>>> jane.age
26
Copied! setattr()
Signature
setattr(object, name, value)
Copied! 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
setattr()
function doesn’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:
>>> class Car:
... def __init__(self, make, model):
... self.make = make
... self.model = model
...
>>> toyota = Car("Toyota", "Corolla")
>>> setattr(toyota, "year", 2020)
>>> toyota.year
2020
Copied! setattr()
Common Use Cases
The most common use cases for setattr()
include:
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.
>>> 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
Copied!
In this example, setattr()
helps update the book
object’s attributes based on the provided dictionary, allowing for flexible and dynamic attribute management.
Tutorial
Python's Built-in Functions: A Complete ExplorationIn 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.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4