The setattr() function in Python is used to set an attribute on an object. It takes three arguments:
- Object: The instance of the class on which you want to set the attribute.
- Attribute Name: A string representing the name of the attribute you want to set.
- Value: The value you want to assign to the attribute.
Syntax
setattr(object, attribute_name, value)
How It Works
- If the specified attribute already exists on the object,
setattr()updates its value. - If the attribute does not exist,
setattr()creates a new attribute with the specified name and assigns it the given value.
Example
Here's a simple example to illustrate how setattr() works:
class Person:
def __init__(self, name):
self.name = name
# Create an instance of Person
p = Person("Alice")
# Set a new attribute 'age' using setattr
setattr(p, 'age', 30)
# Check the attributes
print(p.name) # Output: Alice
print(p.age) # Output: 30
In this example:
- We create a
Personobjectpwith anameattribute. - We use
setattr()to add anageattribute top. - Finally, we print both attributes to confirm that
setattr()worked as expected.
If you have any more questions or need further clarification, feel free to ask!
