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

Susan Sarandon
發布: 2024-10-23 08:38:29
原創
269 人瀏覽過

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

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