1. Nested function definitions
There is a special function in Python, which is defined inside the function, and functions such as those defined within other functions are called intrinsic functions, and the function of the inner function is called an external function. We can also define multi-layered nesting functions, which are intrinsic functions that define an intrinsic function. The definition of an intrinsic function is simple, as is the definition of Def, just inside a function, for example:
>>> var=90>>> def test ():d EF Nest (): Global Varprint (var) var+=1return Nest
>>> test () (90)
Note here that execution is test () (), not test (). Nest (), this is because test () returns a nest, and then executes Nest ().
2. Discuss the scope of nested functions
Intrinsic functions can use variables defined by external functions, such as:
def f ():d EF F1 (): X=3print ("Currently in function F1 (): x=", x) def f2 ():p rint ("Currently in function F2 (): x=", x) return F2return F1
>>> f () () ()
Currently in function F1 (): x= 3
Currently in function F2 (): x= 3
But
>>> def f ():
Def f1 ():
X=3
Print ("Currently in function F1 (): x=", X)
def f2 ():
X+=5
Print ("Currently in function F2 (): x=", X)
return F2
Return F1
>>> f () () ()
Currently in function F1 (): x= 3
Traceback (most recent):
File "<pyshell#47>", line 1, in <module>
F () () ()
File "<pyshell#46>", line 6, in F2
X+=5
unboundlocalerror:local variable ' x ' referenced before assignment