Home >Backend Development >Python Tutorial >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>
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!