首頁  >  文章  >  後端開發  >  如何在 Python 中從字串存取類別屬性?

如何在 Python 中從字串存取類別屬性?

Susan Sarandon
Susan Sarandon原創
2024-10-23 08:38:29274瀏覽

How to Access Class Properties from Strings in Python?

在Python 中從字串存取類別屬性

從字串存取類別屬性在各種程式設計場景中都是一種有用的技術。考慮以下類別定義:

<code class="python">class User:
    def __init__(self):
        self.data = []
        self.other_data = []

    def doSomething(self, source):
        # Access class property based on string value</code>

解決方案:

要基於字串值動態存取類別屬性,可以使用 getattr() 函數。具體方法如下:

<code class="python">x = getattr(self, source)</code>

在此範例中,self 表示 User 類別的實例,source 是一個字串,其中包含要存取的屬性的名稱。例如,如果 source 是 'other_data',則程式碼將檢索 self.other_data 屬性。

實作:

在doSomething() 方法中,您可以實作屬性存取如下:

<code class="python">def doSomething(self, source):
    if hasattr(self, source):
        x = getattr(self, source)</code>

這會在存取來源屬性之前:

這會在存取來源屬性之前檢查類別中是否存在。

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

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