首頁  >  文章  >  後端開發  >  如何從 Python 中的字串輸入動態存取類別屬性?

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

Linda Hamilton
Linda Hamilton原創
2024-10-23 08:42:02613瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn