Home >Backend Development >Python Tutorial >How Can I Access and Modify Object Attributes in Python Using Strings?
Accessing Object Attributes by String
Consider a scenario where you have an object t and a string x representing an attribute name of t. How can you retrieve or modify the value of this attribute?
The Python language provides convenient mechanisms for this operation:
getattr() and setattr() Functions:
Python offers the getattr() and setattr() built-in functions for accessing and modifying object attributes dynamically. These functions take the following syntax:
getattr(object, attrname) # Retrieves the attribute value setattr(object, attrname, value) # Sets the attribute value
Example:
In the given code snippet:
class Test: def __init__(self): self.attr1 = 1 self.attr2 = 2 t = Test() x = "attr1"
To get the value of the attribute represented by x, you can use:
x = getattr(t, 'attr1')
To set the value of the attribute represented by x to 21:
setattr(t, 'attr1', 21)
This approach provides a flexible and dynamic way to access and modify object attributes, especially useful when working with dynamic data structures or strings representing attribute names.
The above is the detailed content of How Can I Access and Modify Object Attributes in Python Using Strings?. For more information, please follow other related articles on the PHP Chinese website!