【问题标题】:In Python, how do I get a variable via a string representation of the name of the variable?在 Python 中,如何通过变量名称的字符串表示来获取变量?
【发布时间】:2014-08-01 20:16:40
【问题描述】:

我使用的是 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 的固有混淆性质,我深表歉意。

【问题讨论】:

  • 值得注意的是,这通常表明存在更大的设计问题——这通常意味着您需要数据结构而不是属性。您实际上想通过此实现什么目标?
  • 您应该始终尝试将数据保留在变量名称之外:nedbatchelder.com/blog/201112/…

标签: python string class self hasattr


【解决方案1】:

如果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),在少数有限情况下,是code smell。这几乎很可能意味着您的设计存在缺陷。

【讨论】:

  • 请注意,locals()globals() 调用很少是一个好主意。
  • 我完全同意。
【解决方案2】:

我认为这就是你所追求的,但不完全确定......

print getattr(self, s)

您还可以使用它来指定在不存在时返回的内容。见getattr docs

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

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2018-10-20
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    相关资源
    最近更新 更多