【问题标题】:Iteratively convert dictionary into set of global variables迭代地将字典转换为一组全局变量
【发布时间】:2019-07-28 00:42:22
【问题描述】:

我想迭代地将字典转换为匹配的全局变量,如下所示:

# starting dictionary
parameters = {
    'a': 3,
    'b': 4
}

# result
a = 3
b = 4

现在我非常清楚与全局变量相关的注意事项:这并不是一种“生产”解决方案,而是一种使用大量现有代码库进行优化而无需进行大量重组的方法。

有什么想法吗?

【问题讨论】:

    标签: python global-variables global


    【解决方案1】:

    你可以使用本地人:

    locals().update({'test': 2})
    

    结果:

    >>test
    >>2
    

    【讨论】:

      【解决方案2】:
      # starting dictionary
      parameters = {
          'a': 3,
          'b': 4
      }
      
      locals().update(parameters)
      print(a)
      print(b)
      

      输出

      3
      4
      

      a, b = parameters['a'], parameters['b']
      

      Consider the Bunch alternative::

      class Bunch(object):
          def __init__(self, parameters):
              self.__dict__.update(parameters)
      
      parameters = {
          'a': 3,
          'b': 4
      }
      vars = Bunch(parameters)
      print(vars.a, vars.b)
      

      输出

      3 4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-11
        相关资源
        最近更新 更多