簡體   English   中英

在Python中,如何通過變量名稱的字符串表示形式獲取變量?

[英]In Python, how do I get a variable via a string representation of the name of the variable?

我正在使用Python 2.7。

以下面的代碼為例:

class Apple:
    def __init__(self, n):
        self.n = n
    def printVariable(self, s): # print variable named s
        if hasattr(self, s):
            print ...

我將用...代替什么來打印self.'s' 例如,如果我調用printVariable('n') ,我將用什么代替...打印n

當然, self.s將不起作用,因為首先沒有self.s屬性,但更重要的是,這將打印一個不同的變量,而不是變量self.'s'我想打印其名稱由表示的變量傳遞給方法的字符串s

對於這個問題中self.sself.'s's的內在混亂特性,我感到抱歉。

如果hasattr(self,s)足以滿足您的需求,那么您需要getattr()

if hasattr(self, s):
    print getattr(self, s)

實際上,根據您的確切要求,您可能可以完全跳過hasattr 如果缺少屬性, getattr()將使用默認值返回:

print gettattr(self, s, 'No such attribute: '+s)

如果要在當前對象之外(例如,在本地范圍或全局范圍內,或在另一個對象中)查找變量,請嘗試以下方法之一:

locals()[s]
globals()[s]
getattr(other_object, s)

注意:使用locals()globals()和在較小范圍內使用hasattr(self,s) (在少數情況下)是一種代碼氣味 這幾乎很可能意味着您的設計存在缺陷。

我認為這就是您所追求的,但是並不確定...

print getattr(self, s)

您也可以使用它指定不存在的返回值。 請參閱getattr文檔

print getattr(self, s, 'default value')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM