函数将添加到当前命名空间,就像添加任何其他名称一样.这意味着您可以在函数或方法中使用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'
不同之处在于,当导入时执行顶级类主体时,将立即定义垃圾邮件.
像全局的所有用途一样,您可能想重新考虑问题并找到解决问题的另一种方法.例如,您可以返回如此创建的函数.
演示:
>>> def create_global_function():
... global foo
... def foo(): return 'bar'
...
>>> foo
Traceback (most recent call last):
File "", line 1, in
NameError: name 'foo' is not defined
>>> create_global_function()
>>> foo
>>> foo()
'bar'
>>> class ClassWithGlobalFunction:
... global spam