【问题标题】:python string and variablepython字符串和变量
【发布时间】:2012-11-24 13:27:06
【问题描述】:

在 Python 中有没有其他方法可以将字符串更改为变量? 例如,我有一些变量名为 button1、button2、button3 等,我想在循环中对它们进行操作。如果我不想使用 eval,还有什么合适的吗?

【问题讨论】:

    标签: python string variables


    【解决方案1】:

    globalslocals 返回当前命名空间的字典映射。

    例如:

    a = 1
    print globals()['a']  #1
    

    如果变量是在模块级别定义的,则应使用globals,其他所有内容均应使用locals。在你的情况下,我认为locals()['button1'] 会成功。


    话虽如此,首先将按钮放在字典中可能是一个更好的主意。

    【讨论】:

    • 谢谢。我认为将它们放入字典是一个很好的解决方案。
    • 如果您对它可能有什么问题发表评论,我很高兴改进这个答案:)
    • 抱歉来晚了。再次感谢你。我已经解决了。
    【解决方案2】:

    这不是你问的问题,而是有什么问题:

      for btn in (button1, button2, button3):
          do_something(btn)
    

    【讨论】:

      【解决方案3】:

      globals()locals() 函数返回可用于直接操作全局和局部变量的字典:

      # sets the global variable foo (in the scope of the module) to 1
      # equivalent to
      #   foo = 1
      # outside a functions
      globals()['foo'] = 1
      
      # gets the local variable bar (in the scope of the current function)
      # equivalent to
      #   print bar
      # inside a function
      print locals()['bar']
      

      当您在函数外部使用locals() 时,它相当于使用globals()

      如果你想操作一个对象的属性,你可以使用getattr(obj, name)setattr(obj, name, value)来代替:

      # equivalent to
      #   print foo.x
      print getattr(foo, 'x')
      
      # equivalent to
      #   foo.x = 45
      setattr(foo, 'x', 45)
      

      编辑:正如DSM 所指出的,使用locals() 不能可靠地用于在函数中设置变量值。无论如何,将所有按钮都包含在单独的字典中也会更聪明。

      【讨论】:

      • 你不能依赖这种方式修改locals(),因为the docs警告。尝试在函数中更改 bar 并在 locals()['bar'] 赋值之前和之后粘贴 print bar
      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多