python - How are functions inside functions called? And can I access those functions or they work like "helper methods"? -
i'm studying python through python tutorial , i'm @ classes (chapter 9), during explanation of "scopes , namespaces" got question.
the author give 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 know until now, keyword def used define functions , functions placed inside classes, in case defined function inside function, function inside function called?
is there way can access outside first function? example namespace scope_test contained.
would functions inside functions work "helper methods" called in other programming languages java , c# when private methods?
functions can defined anywhere. not need defined inside classes, can defined inside other functions too; commonly referred nested functions in case.
you cannot access nested functions outside scope_test() function; local variables. limitation applies all local variables in function. example, spam name defined inside scope_test also not accessible outside of function. exist duration of function local scope.
the function make them available returning function. python functions first class objects, can pass them around other values, can assign them other names, or can return them.
you call them helper functions if want to; in python nested functions if want make use of nested scope, referring variables defined in parent scope. decorators make use of (defining configuration wrapper function), event handlers.
Comments
Post a Comment