In this tutorial, we will delve into one of Python’s built-in functions, setattr()
. This function is a part of Python’s attribute management functions alongside getattr()
, hasattr()
, and delattr()
.
What is setattr()?
The setattr()
function in Python sets the value of a specified attribute for an object. The syntax for this function is as follows:
setattr(object, name, value)
This function takes three parameters:
- object: The object whose attribute is to be set.
- name: A string that contains the attribute’s name.
- value: The value that you want to set for the attribute.
A Basic Example of Using setattr()
class Person:
age = 23
name = "Adam"
person = Person()
print('Before modification:', person.name)
# Setting attribute name to 'John'
setattr(person, 'name', 'John')
print('After modification:', person.name)
# Outputs: After modification: John
In this example, we first define a class named Person with two attributes: age and name. We then create an instance of this class and use the setattr() method to change the value of the ‘name’ attribute from ‘Adam’ to ‘John’.
Dynamically Adding New Attributes with setattr()
Besides modifying existing attributes, you can also use setattr()
to add new attributes to an object dynamically. Let’s see how:
class Person:
age = 23
name = "Adam"
person = Person()
# Adding attribute 'gender'
setattr(person, 'gender', 'Male')
print('Person has gender?:', hasattr(person, 'gender'))
# Outputs: Person has gender?: True
In this example, we added a new attribute named ‘gender’ to the person object using setattr(). We then used the hasattr() function to check if the person object now has a ‘gender’ attribute.
Conclusion
The setattr()
function is a powerful tool in Python that allows you to modify and add attributes to objects on the fly. It’s part of Python’s dynamic nature and can be particularly useful when you’re working with objects whose structure you don’t know until runtime.
We hope this tutorial helped you understand how to use the setattr()
function in Python. Happy coding!