使全局Python函数中的所有变量 [英] Make all variables in a Python function global

查看:225
本文介绍了使全局Python函数中的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以让函数全局变量中的所有变量?

Is there a simple way to make all variables in a function global?

我有一个函数中有20个奇数变量,不管怎样,我都会给自己留下好的代码......)

I have 20 odd variables in a function and naming them global one by one doesn't make nice code... to me anyway :)

推荐答案

警告:不要在家里试试这个, 。

在正常的日常编程过程中没有正当的理由去做以下事情。请仔细阅读这个问题的其他答案,以获得更实际的选择。

Warning: Don't try this at home, you might burn it down.

There is no legitimate reason to do the following in the course of normal day-to-day programming. Please review the other answers to this question for more realistic alternatives.

我几乎无法想象为什么你会想要这样做,但这是一种方法:

I can barely imagine why you would want to do this, but here is a way to do it:

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函数中的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆