Home >Backend Development >Python Tutorial >How to Access Class Property Dynamically Using String in Python?
When working with Python, you may encounter situations where you need to access a class property dynamically based on a string. One such use case is accessing different class members based on a user-provided string value.
In such scenarios, you can utilize the getattr function. Consider the following class as an example:
<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</code>
Within the doSomething method, you can access the class property dynamically using getattr:
<code class="python">x = getattr(self, source)</code>
In this case, x will be assigned the value of the class property other_data if source equals 'other_data'. This is because getattr takes an object and a string that represents the property name, and returns the value of the property.
Using getattr provides a convenient and dynamic way to access class properties based on a string. It allows you to avoid using hardcoded property names, making your code more flexible and reusable.
The above is the detailed content of How to Access Class Property Dynamically Using String in Python?. For more information, please follow other related articles on the PHP Chinese website!