如何從 Python 中的字串輸入動態存取類別屬性?

Linda Hamilton
發布: 2024-10-23 08:42:02
原創
611 人瀏覽過

How to Access Class Properties Dynamically from String Input in Python?

Python:從字串存取類別屬性

在Python 中,您可能會遇到需要使用字串存取類別屬性的情況。例如,您可能有一個這樣的類別:

<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>
登入後複製

您想要為 doSomething 中的來源參數傳遞一個字串值並存取具有相同名稱的類別成員。

解:

這個問題的理想解法是使用getattr 函數:

<code class="python">x = getattr(self, source)</code>
登入後複製

getattr 有兩個參數:你想要存取其屬性的物件和字串形式的屬性名稱。在您的情況下,您將使用 self 作為第一個參數,使用 source 作為第二個參數。

無論來源字串引用 self 的哪個屬性(包括範例中的 other_data),此方法都將無縫運作。

以上是如何從 Python 中的字串輸入動態存取類別屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!