1. Execute code
The following examples are executed by executing the following code, which requires the following execution code to be placed behind the instance code.
A = Outer_func ()
= Outer_func ()
Print ("Call B ()") b () b () b ()
2. nonlocal not used
def Outer_func (): = 3 def Inner_func (): + = 1 print("count" , Count) return Inner_func # output>>> # Count + = 1#unboundlocalerror:local variable ' count ' referenced before assignment
3. Using nonlocal
defOuter_func (): Count= 3defInner_func (): nonlocal count Count+ = 1Print("Count", Count)returnInner_func#output>>>#Call A ()#Count 4#Count 5#Count 6#Call B ()#Count 4#Count 5#Count 6
4. Using Global (Error)
def Outer_func (): = 3 def Inner_func (): Global count + = 1 print( " Count " , Count) return Inner_func # output>>> # Count + = 1# nameerror:name ' count ' is not defined
5. Using Global (Success)
Count = 3defOuter_func ():defInner_func ():GlobalCount Count+ = 1Print("Count", Count)returnInner_func#output>>>#Call A ()#Count 4#Count 5#Count 6#Call B ()#Count 7#Count 8#Count 9
[Timlinux] The role of Python nonlocal and global