Understanding of Python function scopes, nested functions, closure functions, higher order functions, and adorners

Source: Internet
Author: User
Tags closure function definition ming variable scope python decorator

First, preface

The concepts of closures, higher-order functions, function nesting, and decorators, as well as their relationship 1:30, are difficult to understand during the initial learning of Python, which is the essence of the Python function and takes some time to comprehend. Which decorator is the most difficult to understand, why? Because only the variable scope, the closure function, nested functions, high-order functions are understood, the adorner can be more easily understood. They are a system of knowledge, must be a system of learning. Below we will gradually, layer by layer stripping, will eventually understand all the above concepts.

Two, nested functions

Speaking of nested functions there must be someone to answer: "is not the function inside the call function?" Like this:

def func1():    print ‘func1‘def func2():    print ‘func2‘    func1()func2()

The real function nesting should be, in a function also defined a function.

def outer():     print ‘outer‘    def inner():       print ‘inner‘outer()

Like this, a function is created in the body of a function, and this form belongs to the function nesting.

Iii. function scope 1, scope classification

To understand the scope of the variable, the scope of the variable is generally divided into two categories, global scope and local scope, but in depth, the scope of the variable from outside to inside is:

L(local) 局部作用域        E(Enclosing) 闭包函数外的函数中     G(Global) 全局作用域    

Follow the LEGB principle: to l–> e–> g–>b rules to find, that is: in the local can not find, will go to the local nesting scope (such as closures), and then can not find the overall search, and then to the built-in search. What do you mean? To illustrate:

a =int(‘3‘) #内建作用域a = 2         #全局作用域def outer():    b = 3   #嵌套作用域(闭包数外外部函数中的作用域)    def inner():         c = 3   #局部作用域        return ‘inner‘    return inner()outer()
2, under what circumstances will create a new scope

In Python, modules (module), Classes (Class), Functions (Def, lambda) produce new scopes, and other blocks of code do not produce scopes, that is, similar conditional judgments (IF.....ELSE), loop statements (for x in data), Variables such as exception snapping (Try...catch) can be used globally.

dataList = [1, 2, 3, 4]for data in dataList:    a = 1   #for循环中的变量a    b = data + aprint(a) #在函数外也可视为全局变量使用
3. Variable Scope note

1. Local variables cannot modify global variables unless the global variable is added

(1) Not using global

a = 1def demo():    # IDE提示a = 123:This inspection detects shadowing names defined in outer scopes    # 大概意思是给变量取的这个名字,可能会冲突,它是函数外部的变量    a = 123    print(a)demo()print(a)运行结果是1231全局变量a的值还是1,没有被改变

(2) using global

a = 1def demo():    global a    a = 123    print(a)    demo()print(a)运行结果是123123全局变量a的值被修改

2, local variables cannot modify nested variables, unless the use of the Nonlocal,nonlocal keyword on an external variable is similar to the Global keyword, modify the variables in the nested scope (enclosing scope, outer non-global scope)
(1) nonlocal not used

def outer():    num = 10    def inner():        num = 100        print(num)    inner()    print(num)outer()运行结果为10010闭包函数外的变量num值未被修改

(2) using nonlocal

def outer():    num = 10    def inner():        nonlocal num   # nonlocal关键字声明        num = 100        print(num)    inner()    print(num)outer()运行结果为100100闭包函数外的变量num值被修改
Closure function definition of closed packet function

The closure function can be understood as: in an intrinsic function, the local variable is to the outer scope (where the outer scope refers to the global scope!). Instead of a nested scope), the inside of the function can be understood to be a closed packet. This intrinsic function is the closure function.

def outer():    num = 10    def inner():        print(num)       print(num)outer()
The closure function requires a little attention:

1, inside the closure function, the default is not to modify the external scope of the variable!! (Use the Nonlocal keyword to declare exceptions)

The IDE will then report the following error:

2. The variable a defined in the closure function does not affect the A variable of the outer scope.

def outer():    num = 10    def inner():        num = 100        print(num)    inner()    print(num)outer()运行结果为10010
Higher-order functions what are higher-order functions

All of the following two conditions are high-order functions:

1, another function as a parameter of this function
2. The return value of this function is a function

def test1():    print "allen" def test2(func):    return test1
Decorative Device

Finally the big Boss finally appeared, if the above concepts are understood, the adorner is actually very simple. Adorners are also a function, but this function is more special. Of course, the adorner can also be a class, below we will talk about. First of all we need to know why Python has the concept of adorners, and like Java does not have this concept, that is because the function of Python can be referenced as a variable , this sentence two meanings:
1, the function can be used as a parameter of another function
2, function can be used as the return value of another function

Let's look at a story, "The Nativity of the Python decorator," to see what an adorner is?

If Xiao Ming classmate just learned not to Python to the company to complete a lot of requirements, the following is his completion of one of the requirements and write a function:

import timedef foo():     print(‘foo run finish.......‘)    time.sleep(3)

Then demand came, asked Xiao Ming students to calculate the time of all functions, Xiao Ming smiled, this is not simple, readily agreed. So Chi Chi big change a pass. The eldest brother after a period of time, asked Xiao Ming needs to realize no, Xiao Ming fart fart to take out the code:

def foo():    start = time.time()    print(‘foo run finish.......‘)    time.sleep(3)    end = time.time()    print(‘time long %s‘ % (end - start))foo()............五百个函数同上

The eldest brother looked after, know xiaoming is novice, also did not criticize him, give Xiao Ming said, why do not have a clever way, let Xiao Ming take back oneself want how to redo. Xiao Ming's classmates have rewritten a version:

def foo():    print(‘foo run ok....‘)    time.sleep(3)def comp_time(func):    start = time.time()    func()    end = time.time()    print(‘time long %s‘ % (end - start))comp_time(foo)

Leaders looked after the progress, but still not good enough, would have to call Foo () to complete a function, after the modification is called Comp_time (), modified the original method of invocation, let xiaoming continue to change. Xiaoming has a version:

def foo():    print(‘foo run ok....‘)    time.sleep(3)def comp_time(func):    def print_time():        start = time.time()        func()        end = time.time()        print(‘time long %s‘ % (end - start))        return end - start    return print_timefoo = comp_time(foo)foo()

The leader looked after the feeling that Xiao Ming still has two down, but has not reached the expected, and let Xiao Ming again change, Xiao Ming this class baffled, how to change? But not discouraged Xiao Ming, through the python from the beginning to abandon the treasure, after another version:

def comp_time(func):    def print_time():        start = time.time()        func()        end = time.time()        print(‘time long %s‘ % (end - start))        return end - start    return print_time@comp_timedef foo():    print(‘foo run ok....‘)    time.sleep(3)foo()

The boss looked after, applauded, to Xiao Ming said: Young man is good, dry beautiful, a good reward you, stay at night to continue to work overtime

The story is over.

Our decorator is also born, the adorner is a function or class that helps this function to expand functionality without changing the contents and invocation of the original function. Blunt * * * closure function + higher order function + nested function [email protected] syntax sugar = Adorner * *

The adorner combined with the last version code in the story, the invocation and content of Foo () did not change, except that a syntactic sugar was used on the basis of the original function @comp_time, and the Comp_time () function helped the Foo () function expand the function of calculating execution time. The Comp_time () function is an adorner. If you have not yet read what is the adorner, then look again from the beginning, if not again on both sides, and then do not understand, I have no way.

Let's take a look at how the decorated function takes parameters:

def comp_time(func):    def print_time(name):        start = time.time()        func(name)        end = time.time()        print(‘%s time long %s‘ % (name,end - start))        return end - start    return print_time@comp_timedef foo(name):    print(‘foo run ok....‘)    time.sleep(3)foo()

You need to add a formal parameter to the decorated function, the adorner's inner function, and the argument to the place where it was called.

How do adorners take parameters:

def user_log(name):    def comp_time(func):        def print_time():            start = time.time()                func()                end = time.time()                print(‘time long %s‘ % (end - start))                return end - start        return print_time       return comp_time@comp_time(name)def foo():    print(‘foo run ok....‘)    time.sleep(3)foo()

On top of that, the adorner can also be a class:

class Foo(object):    def __init__(self, func):        self._func = func    def __call__(self):        print(‘class decorator runing‘)        self._func()        print(‘class decorator ending‘)@Foodef bar():    print(‘bar‘)bar()

The contents of the decorator are finished.

Understanding of Python function scopes, nested functions, closure functions, higher order functions, and adorners

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.