Home >Backend Development >Python Tutorial >How to Access Class Properties Dynamically Using String Variables in Python?

How to Access Class Properties Dynamically Using String Variables in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 08:37:01247browse

How to Access Class Properties Dynamically Using String Variables in Python?

Accessing Class Properties from Strings in Python

When working with classes, it may be necessary to access properties dynamically based on the value of a string variable. Consider the following class:

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

    def doSomething(self, source):
        # Task: access self.other_data if source is 'other_data'</code>

To dynamically access a class property based on a string variable, you can use the getattr function. Here's how it works:

<code class="python">x = getattr(self, source)</code>
  • self is the class instance.
  • source is the string variable containing the name of the property to access.

In your example, if source is 'other_data', getattr will return the value of self.other_data. This approach works for any valid attribute name of the class, including both self.data and self.other_data in your case.

The above is the detailed content of How to Access Class Properties Dynamically Using String Variables 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