Home >Backend Development >Python Tutorial >How to Access Class Properties Dynamically from String Input in Python?
Python: Accessing Class Properties from Strings
In Python, you may encounter situations where you need to access class properties using strings. For instance, you may have a class like this:
<code class="python">class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): # How to access self.other_data if source = 'other_data'?</code>
You want to pass a string value for the source parameter in doSomething and access the class member with the same name.
Solution:
The ideal solution to this problem is to use the getattr function:
<code class="python">x = getattr(self, source)</code>
getattr takes two arguments: the object whose property you want to access and the name of the property as a string. In your case, you would use self as the first argument and source as the second.
This approach will work seamlessly regardless of which attribute of self is referenced by the source string, including other_data in your example.
The above is the detailed content of How to Access Class Properties Dynamically from String Input in Python?. For more information, please follow other related articles on the PHP Chinese website!