advanced function

 Temporary namespace
 name = 'alex'
 age = 12
 def funcl():
  name1 = 'wusir'
  age1 = 34
 funcl() #Temporary
 namespace: temporary namespace, local namespace, the relationship between variables and values ​​stored in functions , as the execution of the function ends, the temporary namespace ends.

 Namespaces: global namespace, local namespace, built-in namespace.
 scope: global scope: global namespace, built-in namespace
   local scope: local namespace

 Load order, value order.
 Loading order: Built-in namespace---"Global namespace---"Local namespace (when the function is executed)
 Value order:
 Local --"Global--"Built-in
 
 globals #Global namespace
 
 locals #Keyword
 
 : global nonlocal
 You can use global variables locally, but you cannot change
 
 global. Declare a global environment variable, and modify the global variable in the function.
 def funcl():
    global name
    name = 'alex'
    return
 funcl()
 print(name)

 
 nonlocal
 1. Global variables cannot be modified
 2. In the local scope, reference and modify the variables of the parent scope (or the outer scope non-global scope), and which layer is referenced, from which layer and The following variables are all changed.
 
 def funcl():
 name1 = 'alex'
    print('+',name1) #<--First step
    def inner(): nonlocal name1 #If
        you remove this
        name1 = 'wusir'
        print('-',name1)
    inner() #<--The second step
    print('*',name1) #<--The third step
 funcl()

 Output result
 + alex
 - wusir
 * wusir #The output here will become * alex
 
function name - both the function of the return function and the function of the variable
1. You can assign each other
 def funcl():
  print(666)
 f1 = funcl
 f1 ()
 
 2. Can be used as a function parameter
 def func1():
  print(666)
  
 def func2(argv):
  args()
  print(777)

 666
 777
 
 3. Can be used as a parameter of the container class data type
 
 def func1():
  print(666)
 def func2():
  print(777)
 def func3():
  print(888)
 l1 = [func1,func2,func3] #As Container
 for i in l1:
  i()
 result
 666
 777
 888
 
 4. The function name can be used as the return value of the function
 def func1():
  print(666)
 def func2(argv):
  print(777)
  return argv
 ret = func2(func1)
 ret()
 result
 777
 666

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324614060&siteId=291194637