In Python, you may encounter situations where you need to access or set the attributes of an object using a string that represents the attribute name. This capability is particularly useful when dealing with dynamic attribute handling.
To retrieve the value of an attribute given its name as a string, use the getattr function:
x = getattr(t, 'attr1') # retrieves the value of t's attr1 attribute
To assign a new value to an attribute using its name as a string, use the setattr function:
setattr(t, 'attr1', 21) # sets t's attr1 attribute to 21
Notably, the same technique also applies to accessing methods and calling modules by their names as strings. This is because Python treats these entities as "objects" with "attributes" that behave the same as regular attributes.
In summary, getattr and setattr provide a powerful way to dynamically access and modify object attributes based on their names stored as strings.
The above is the detailed content of How Can I Access and Modify Python Object Attributes Using Strings?. For more information, please follow other related articles on the PHP Chinese website!