What are enclosing functions?

后端 未结 3 1524
再見小時候
再見小時候 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: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 "", line 1, in 
    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?

提交回复
热议问题