What are enclosing functions?

后端 未结 3 1523
再見小時候
再見小時候 2021-02-01 11:14

According to the python tutorial, functions look for variable names in the symbol tables of enclosing functions before looking for global functions:

The

相关标签:
3条回答
  • 2021-02-01 12:04

    The concept of an enclosing function is key in understanding the idea of closures. Because python does not have fully featured lambdas (they only allow expressions and not statements), having nested functions to pass on to other functions is a common use case:

    def receiving_function(f):
        f()
    
    def parent_function():
        y = 10
    
        def child_function():
            print(y)
    
        receiving_function(child_function)
    

    will print 10 as before. This is a common instance of a closure, where the enclosing function "hands off" it's variables to the enclosed function. In the example above, this function is passed off to the receiving_function along with the non-local variable y.

    0 讨论(0)
  • 2021-02-01 12:04

    Enclosing functions are functions nested in functions. We usually use it to get better encapsulation. That is enclosing functions are not visible for other functions.

    0 讨论(0)
  • 2021-02-01 12:08

    The reason you cannot call child_function by itself, is that it is defined inside the parent_function. All python variable declarations use block scope, and declaring a function is no different.

    Consider the following example.

    >>> def parent_function():
    ...    y=10
    ...    def child_function():
    ...        print y
    ...    child_function()
    
    >>> print y
    Traceback (most recent call last):
      File "<interactive input>", line 1, in <module>
    NameError: name 'y' is not defined
    

    The variable y is not accessible outside the parent_function. Why would you expect that child_function would be any different that y?

    0 讨论(0)
提交回复
热议问题