How are functions inside functions called? And can I access those functions or they work like “helper methods”?

时光怂恿深爱的人放手 提交于 2019-12-13 07:14:26

问题


I'm studying Python through The Python Tutorial and I'm currently at Classes (chapter 9), but during the explanation of "scopes and namespaces" I got a question.

The author give this example:

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

Source: http://docs.python.org/3.3/tutorial/classes.html#scopes-and-namespaces-example

From what I know until now, the keyword def is used to define functions and functions are placed inside classes, but in this case he defined a function inside a function, so what is this function inside the another function called?

Is there a way I can access it from the outside the first function? For example from the namespace where scope_test is contained.

Would this functions inside functions work like "helper methods" called like that in other programming languages like Java and C# when they are private methods?


回答1:


Functions can be defined anywhere. They do not need to be defined inside classes, they can be defined inside other functions too; the are commonly referred to as nested functions in that case.

You cannot access the nested functions from outside the scope_test() function; they are local variables. That limitation applies to all local variables in a function. For example, the spam name defined inside scope_test is also not accessible outside of the function. They exist only for the duration of the function local scope.

The function could make them available by returning the function. Python functions are first class objects, so you can pass them around like other values, you can assign them other names, or you can just return them.

You could call them helper functions if you want to; in Python you normally nested functions if you want to make use of the nested scope, referring to variables defined in a parent scope. Decorators often make use of this (defining configuration for a wrapper function), as do event handlers.



来源:https://stackoverflow.com/questions/16358375/how-are-functions-inside-functions-called-and-can-i-access-those-functions-or-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!