Detailed explanation of python function call order, higher-order function, nested function and closure

Keywords: Python

One: function call order: similar to other high-level languages, Python does not allow to reference or call functions before they are declared
Error demonstration:

def foo():
    print 'in the foo'
    bar()
    
foo()

//Report errors:
in the foo

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    foo()
  File "<pyshell#12>", line 3, in foo
    bar()
NameError: global name 'bar' is not defined

 

def foo():
    print 'foo'
    bar()
foo() #bar has not been defined yet. foo is executed here
def bar(): 
  
print 'bar'
Report errors: NameError:
global name 'bar' is not defined

 

Correct demonstration: (note that in order to explain the execution of python, the function foo has declared bar and foo before calling, so there is no order between bar and foo.)

 

def bar():
    print 'in the bar'
def foo():
    print 'in the foo'
    bar()
    
foo()

def foo():
    print 'in the foo'
    bar()
def bar():
    print 'in the bar'
foo()

 

Two: higher order function

If one of the following conditions is satisfied, the function can be of higher order

  1. A function is passed as an argument to another function

  2. The return value of function contains n functions, n > 0

     

High order function demonstration:

def bar():
    print 'in the bar'
def foo(func):
    res=func()
    return res
foo(bar)

The advantages of higher order functions:

def foo(func):
    return func

print 'Function body is %s' %(foo(bar))
print 'Function name is %s' %(foo(bar).func_name)
foo(bar)()
#foo(bar)() Equate to bar=foo(bar)Then? bar()
bar=foo(bar)
bar()

Three: embedded function and variable scope:

Definition: create another function within a function body, which is called an embedded function (based on python support for static nested fields)

Function nesting demonstration:

def foo():
    def bar():
        print 'in the bar'

    bar()

foo()
# bar()

Local scope and global scope access order

x=0
def grandpa():
    # x=1
    def dad():
        x=2
        def son():
            x=3
            print x
        son()
    dad()
grandpa()

The influence of local variable modification on global variable

y=10
# def test():
#     y+=1
#     print y

def test():
    # global y
    y=2
    print y

test()
print y


def dad():
    m=1
    def son():
        n=2
        print '--->',m + n
    print '-->',m
    son()
dad()

 

Closure: if a variable in an internal function is referenced in the external scope (but not in the global scope), the internal function is considered to be a closure
def counter(start_num=0):
    count=[start_num]
    def incr():
        count[0]+=1
        return count[0]
    return incr

print counter()
print counter()()
print counter()()
c=counter()
print c()
print c()

Posted by LikPan on Mon, 09 Dec 2019 06:02:27 -0800