Home >Backend Development >Python Tutorial >How Can I Access and Modify Object Attributes in Python Using Strings?

How Can I Access and Modify Object Attributes in Python Using Strings?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 08:38:11328browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn