首頁  >  文章  >  後端開發  >  如何在Python中使用字串變數動態存取類別屬性?

如何在Python中使用字串變數動態存取類別屬性?

Patricia Arquette
Patricia Arquette原創
2024-10-23 08:37:01152瀏覽

How to Access Class Properties Dynamically Using String Variables in Python?

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

使用類別時,可能需要根據 a 的值動態存取屬性字串變數。考慮以下類別:

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

    def doSomething(self, source):
        # Task: access self.other_data if source is 'other_data'</code>

要基於字串變數動態存取類別屬性,可以使用 getattr 函數。它的運作原理如下:

<code class="python">x = getattr(self, source)</code>
  • self 是類別實例。
  • source 是包含要存取的屬性名稱的字串變數。

在您的範例中,如果來源是“other_data”,則 getattr 將傳回 self.other_data 的值。此方法適用於類別的任何有效屬性名稱,包括您的情況下的 self.data 和 self.other_data 。

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

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