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

Barbara Streisand
Release: 2024-10-23 08:39:01
Original
690 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!