How to define global function in Python?

后端 未结 3 684
说谎
说谎 2020-12-10 01:47

Is there a way to define a function to be global from within a class( or from within another function, as matter of fact)? Something similar to defining a global variable.

3条回答
  •  孤街浪徒
    2020-12-10 02:32

    Functions are added to the current namespace like any other name would be added. That means you can use the global keyword inside a function or method:

    def create_global_function():
        global foo
        def foo(): return 'bar'
    

    The same applies to a class body or method:

    class ClassWithGlobalFunction:
        global spam
        def spam(): return 'eggs'
    
        def method(self):
            global monty
            def monty(): return 'python'
    

    with the difference that spam will be defined immediately as top-level class bodies are executed on import.

    Like all uses of global you probably want to rethink the problem and find another way to solve it. You could return the function so created instead, for example.

    Demo:

    >>> 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
    ...     def spam(): return 'eggs'
    ...     def method(self):
    ...         global monty
    ...         def monty(): return 'python'
    ... 
    >>> spam
    
    >>> spam()
    'eggs'
    >>> monty
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'monty' is not defined
    >>> ClassWithGlobalFunction().method()
    >>> monty()
    'python'
    

提交回复
热议问题