将函数添加到当前名称空间,就像将添加任何其他名称一样。这意味着您可以global
在函数或方法中使用关键字:
def create_global_function():
global foo
def foo(): return 'bar'
同样适用于类主体或方法:
class ClassWithGlobalFunction:
global spam
def spam(): return 'eggs'
def method(self):
global monty
def monty(): return 'python'
区别spam
将在导入时执行顶级类主体时立即定义。
像您的所有用途一样,global
您可能想重新思考问题并找到另一种解决方法。例如,您可以 返回 如此创建的函数。
演示:
>>> def create_global_function():
... global foo
... def foo(): return 'bar'
...
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> create_global_function()
>>> foo
<function foo at 0x102a0c7d0>
>>> foo()
'bar'
>>> class ClassWithGlobalFunction:
... global spam
... def spam(): return 'eggs'
... def method(self):
... global monty
... def monty(): return 'python'
...
>>> spam
<function spam at 0x102a0cb18>
>>> spam()
'eggs'
>>> monty
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'monty' is not defined
>>> ClassWithGlobalFunction().method()
>>> monty()
'python'