您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python中定义全局函数?

如何在Python中定义全局函数?

函数添加到当前名称空间,就像将添加任何其他名称一样。这意味着您可以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'
python 2022/1/1 18:44:45 有319人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶