Home  >  Article  >  Backend Development  >  How to Access Class Property Dynamically from a String in Python?

How to Access Class Property Dynamically from a String in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 08:39:01691browse

How to Access Class Property Dynamically from a String in Python?

Access Class Property from String in Python

In object-oriented programming, it may be necessary to access class properties dynamically based on a string input. Consider the following example class:

<code class="python">class User:
    def __init__(self):
        self.data = []
        self.other_data = []

    def doSomething(self, source):
        if source == 'other_data':
            # How to access self.other_data here?</code>

This example aims to access the class member with the name specified in the source string. Here's how it can be achieved:

Using getattr():

The getattr() function allows accessing attributes of an object dynamically. It takes two arguments: the object and a string representing the attribute name. In this case, source is the attribute name:

<code class="python">x = getattr(self, source)</code>

This line retrieves the value of the attribute with the name stored in source. In the example above, it would assign self.other_data to x.

Note: getattr() can work with both data attributes and methods.

The above is the detailed content of How to Access Class Property Dynamically from a String in Python?. 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