问题
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