📜  Python setattr()(1)

📅  最后修改于: 2023-12-03 15:04:08.585000             🧑  作者: Mango

Python setattr()

setattr() is a built-in Python function that allows you to dynamically set an attribute of an object. It takes three arguments: the object whose attribute you want to set, the name of the attribute, and the value you want to set it to.

Syntax
setattr(object, name, value)
  • object: The object whose attribute you want to set.
  • name: The name of the attribute you want to set.
  • value: The value you want to set the attribute to.
Examples

Here are some examples that illustrate how to use setattr():

# create a class
class Person:
    pass

# create an instance of the class
p = Person()

# dynamically set the 'name' attribute
setattr(p, 'name', 'John Doe')
print(p.name)  # Output: John Doe

# dynamically set the 'age' attribute
setattr(p, 'age', 30)
print(p.age)  # Output: 30

In this example, we create a class called Person, create an instance of the class, and then dynamically set the name and age attributes using setattr(). Finally, we print out the values of these attributes.

Dynamic Attribute Creation

One of the main use cases for setattr() is dynamic attribute creation. For example, you might be working with an API that returns JSON data and you want to create a Python object with attributes that correspond to the keys in the JSON data.

Here's an example:

import json

# example JSON data
data = '{"name": "John Doe", "age": 30}'

# convert JSON data to a Python dictionary
data_dict = json.loads(data)

# create a class dynamically
class Person:
    pass

# create an instance of the class
p = Person()

# dynamically set attributes using data from the dictionary
for k, v in data_dict.items():
    setattr(p, k, v)

# print out the values of the attributes
print(p.name)  # Output: John Doe
print(p.age)   # Output: 30

In this example, we first convert JSON data to a Python dictionary using the json.loads() function. We then create a class called Person dynamically using the class keyword. We create an instance of the class, and then use a for loop to dynamically set attributes on the object using the setattr() function and the data from the dictionary. Finally, we print out the values of the attributes.

Conclusion

In summary, setattr() is a useful Python function that allows you to dynamically set attributes on objects. This can be especially useful for creating objects dynamically based on data from an external source such as a database or API.