有没有一种简单的方法可以使函数中的所有变量都成为全局变量?
我在一个函数中有 20 个奇怪的变量,并且将它们一个一个地命名为全局变量并不能成为很好的代码……无论如何对我来说 :)
最佳答案
警告:不要在家里尝试这个,你可能会烧毁它。
在正常的日常编程过程中没有正当理由执行以下操作。请查看此问题的其他答案以获得更现实的选择。
我几乎无法想象您为什么要这样做,但这里有一种方法:
def f(a, b, c):
d = 123
e = 'crazy, but possible'
globals().update(locals())
def g():
print a, b, c, d ,e
>>> globals()
{'g': <function g at 0x875230>, 'f': <function f at 0x8751b8>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>> g()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in g
NameError: global name 'a' is not defined
>>> f(10, 20, 'blah')
>>> g()
10 20 blah 123 crazy, but possible
>>> globals()
{'a': 10, 'c': 'blah', 'b': 20, 'e': 'crazy, but possible', 'd': 123, 'g': <function g at 0x875230>, 'f': <function f at 0x8751b8>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
关于python - 将 Python 函数中的所有变量设为全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11543297/