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

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

Barbara Streisand
Barbara Streisand原創
2024-10-23 08:39:01692瀏覽

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

Python 中透過字串存取類別屬性

在物件導向程式設計中,可能需要基於字串動態存取類別屬性輸入。考慮以下範例類別:

<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>

此範例旨在存取具有來源字串中指定名稱的類別成員。實作方法如下:

使用 getattr():

getattr() 函數允許動態存取物件的屬性。它需要兩個參數:物件和表示屬性名稱的字串。在本例中,source 是屬性名稱:

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

此行會擷取名稱儲存在 source 中的屬性的值。在上面的範例中,它將 self.other_data 指派給 x.

注意: getattr() 可以使用資料屬性和方法。

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

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