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

How Can I Access and Modify Python Object Attributes Using String Names?

Mary-Kate Olsen
Release: 2024-12-29 07:19:13
Original
714 people have browsed it

How Can I Access and Modify Python Object Attributes Using String Names?

Accessing Object Attributes Using String Names

In Python, accessing attributes of an object is typically done using the dot operator. However, it may be necessary to access attributes using a string corresponding to the attribute name. This can be achieved using the built-in functions getattr and setattr.

To retrieve the value of an attribute given its string name, use getattr. For example:

class Test:
    def __init__(self):
        self.attr1 = 1
        self.attr2 = 2

t = Test()
x = "attr1"
x_value = getattr(t, x)
Copy after login

To set the value of an attribute using its string name, use setattr. For example:

setattr(t, 'attr1', 21)
Copy after login

Note that this technique can also be used to call methods from string names by accessing the method and then calling it normally.

The above is the detailed content of How Can I Access and Modify Python Object Attributes Using String Names?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template