字符串到全局变量?

String to global variable?

我需要将 Dict 的一些键实例化为独立的全局变量。

(在你提出异议之前,让我提一下,这纯粹是为了测试目的,我知道它会污染全局范围。它不是编程技术。)

好的。现在不碍事了。如果我使用像下面这样的简单函数,它就可以工作。

def items_as_vars(obj, lst) :
    for i in lst :
        globals()[i] = obj.g(i)
        print i, obj.g(i)

items_as_vars(obj, ['circle','square'])

print circle

但是当我将其移动到一个单独的文件中成为 class 方法时,它停止工作,即

class blah:
    @staticmethod
    def items_as_vars(obj, lst) :
       for i in lst :
            globals()[i] = obj.g(i)
            print i, obj.g(i)

blah.items_as_vars(obj, ['circle','square'])

print circle

NameError: name 'circle' is not defined

知道为什么吗? "stop working",我的意思是不再实例化全局变量。


更多信息:当 class 在同一个文件中时它似乎工作,但当 class 被导入时它似乎工作!


修改为静态方法,行为相同

您需要使用__builtin__创建跨模块变量。像这样:

class SomeClass(object):
    def g(self, x):
        return x
    def items_as_vars(self, lst) :
        for i in lst :
            import __builtin__
            setattr(__builtin__, str(i), self.g(i))
            print i, self.g(i)

In [9]: import test

In [10]: test.SomeClass().items_as_vars(['x', 'yz'])
x x
yz yz

In [11]: yz
Out[11]: 'yz'