In Python, the setattr() function is a built-in function used to set the value of an attribute of an object. An attribute is a value associated with an object, such as a variable or a method. The setattr() function can be used to set the value of an existing attribute or to create a new attribute.
The basic syntax for the setattr() function is as follows:
|
setattr(object, name, value)
|
where object is the object whose attribute you want to set or create, name is the name of the attribute, and value is the value you want to set the attribute to.
Here are some examples of using the setattr() function:
Example 1: Setting the value of an existing attribute
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
setattr(person, "age", 40)
print(person.age)
|
Output:
40
In this example, a Person class is defined with two attributes: name and age. An instance of the Person class is created with the name "John" and age 30. The setattr() function is then used to set the value of the age attribute to 40. Finally, the value of the age attribute is printed to the console.
Example 2: Creating a new attribute
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
setattr(person, "height", 180)
print(person.height)
|
Output:
180
In this example, a Person class is defined with two attributes: name and age. An instance of the Person class is created with the name "John" and age 30. The setattr() function is then used to create a new attribute called height and set its value to 180. Finally, the value of the height attribute is printed to the console.
Example 3: Setting an attribute dynamically using a variable
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
attr_name = "age"
attr_value = 40
setattr(person, attr_name, attr_value)
print(person.age)
|
Output:
40
In this example, a Person class is defined with two attributes: name and age. An instance of the Person class is created with the name "John" and age 30. Two variables, attr_name and attr_value, are created to store the name and value of the attribute to be set. The setattr() function is then called with the attr_name and attr_value variables to dynamically set the value of the age attribute. Finally, the value of the age attribute is printed to the console.
In conclusion, the setattr() function is a useful tool in Python for setting the value of an attribute of an object or creating a new attribute. The setattr() function can be called on any object in Python, and it allows you to dynamically set the value of an attribute using variables or static values.