Python Development Basics-day7-closure functions and adorners basics

Source: Internet
Author: User
Tags auth closure

Add: global variable declaration and local variable reference

The order in which Python references variables: current scope local variables, outer scope variables, global variables in current module->python built-in variables

The global keyword is used in a function or other local scope to use a globals variable, which can then be modified and used in other actions

X=1 #全局赋值变量 def  foo ():    Global  x #函数内部全局声明变量x    x=111111 1 #函数内部修改全局变量x    print(x) foo ()print(x)

The variables declared by global can be modified at any scope, so it is generally not necessary to avoid such declaration operations.

The nonlocal keyword is used to use an outer (non-global) variable in a function or other scope, and is typically used in nested functions.

def F1 ():     # x=2    def F2 ():        x=3        def f3 ():            nonlocal x            x=1111            #  print (' F3 ', x)        f3 ()         Print('f2', x)    F2 ()    #  Print (' F1 ', x)F1 ()

As above, if nonlocal declaration x is not made inside the F3 function Body, and nonlocal X is commented out, then print in the function body F2 will print "F2 3" and the declared result is "F2 1111".

Closure function

The closure function defines:

functions defined inside a function are called intrinsics, which contain the outer (upper) scope, not the global domain name Word, which is called the closure function

To define a closure function:

defining the basic form of a closure function def external Function name ():    variable    def intrinsic function required by intrinsic function ()  :  #基本函数         reference to external variables     return #不加括号, return memory address

The closure function refers to an intrinsic function

The closure function contains references to external scopes, not global scopes

Characteristics of the closure function: The self-band outward scope, the delay calculation (lazy calculation, when used to calculate)

Example:

Name='Alex'      #全局定义的变量deffunc (): Name='Egon'    #函数func调用的变量, external scope    defBar ():#内部函数        Print(name)#内部函数bar打印name的作用域除了bar函数自己本身, there's the Func function inside    returnBar#调用func函数时的返回值为bar函数本身, rather than the bar function, returns a memory address of bar functionB=func ()#b接收func函数的返回值, that is, the bar function of the memory space, now B is equal to barPrint(b) B ()#执行b即执行bar函数的print (name) print operation, not a globally defined name#print (b.__closure__[0].cell_contents)  #返回作用域空间的第一个变量值#print (b.__closure__)      #作用域空间信息Output Results<function Func.<locals>.bar at 0x0000021ca66cb8c8>Egon

The out-of-the-box scope, that is, the bar function contains the scope of the Func function, and also contains the scope of bar itself, that bar can invoke Name= ' Egon '

The scope is fixed at the time the function is defined, that is, the scope of the B function is always scoped to the bar function definition whenever B () is called.

Adorner Basics

The principle of Program source code: Open to function extension, closed to modify source code

That is, you can extend the functionality on the basis of the source code, and not modify the source code (because the system is on-line to modify the source code, changed the wrong whole)

An adorner is an implementation that is used to extend the functionality of the source code.

The adorner is essentially any callable object, and what is now understood is the function, and the object being decorated can be any callable object.

Adorner function: It is to add new features without modifying the source code of the decorated object and the method of calling the decorated object.

Adorner principle: Do not modify the source code, do not modify the calling method, but also to add new features

Example one: When calling the function index, randomly waits 0-4 seconds to print Hello World

# Original function Import  Time Import Random def index ():    time.sleep (Random.randrange (1,5))    print(' Hello world ' ) index ()

Example two: Extended function statistics The execution time of index, including the time of random wait

Import TimeImportRandomdefIndex_new (func):defTimmer (): Start_time=time.time () func () Stop_time=time.time ()Print('time:%s'% (stop_time-start_time)) returnTimmerdefindex (): #源代码并不改变time.sleep (Random.randrange (1,5))    Print('Hello World') Index=index_new (Index) index () output result: Hello Worldtime:3.000032663345337

Example three: Adorner call syntax

defIndex_new (func):defTimmer (): Start_time=time.time () func () Stop_time=time.time ()Print('time:%s'% (stop_time-start_time)) returnTimmeris called #使用 the @ symbol @index_new#index=index_new (Index)defindex (): Time.sleep (Random.randrange (1,5))    Print('Hello World') index ()

Example four: Define multiple adorners and add multiple function modules

Import TimeImportRandom#Adorner 1: Chronograph moduledefTimmer (func):defwrapper (): Start_time=time.time () func () Stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnwrapper#Adorner 2: Authentication moduledefAuth (func):defdeco (): Name=input ('Name:') Password=input ('Password:')        ifName = ='Egon'  andPassword = ='123':            Print('Login Successful') func ()#wrapper ()        Else:            Print('Login Err')    returndeco#被装饰函数@auth#Index=auth (wrapper) #index =deco #index =auth (wrapper) #index =deco@timmer#Index=timmer (Index) #index =wrapperdefindex ():#Time.sleep (Random.randrange (1,5))Time.sleep (3)    Print('welecome to index page')#并没有调用任何装饰器defHome (): Time.sleep (Random.randrange (1,3))    Print('welecome to HOME page') index ()#deco ()Home ()

When multiple adorners are to be invoked, the order in which they are executed first is the one that is called first, the order is top-down, but the order of the internal computations is bottom

Example five: The source code needs to pass in the parameter, and the value that needs to be returned

Import TimeImportRandom#Decorative DevicedefTimmer (func):defWrapper (*args,**Kwargs): #*args and **kwargs can receive arbitrary parameters, and can not exist, after receiving the function that is passed intact into the func call start_time=time.time () Res=func (*args,**Kwargs) #返回值赋值, the function that needs to be passed in has a return value. stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnRes #抛出返回值returnwrapper#be decorated function@timmerdefindex (): Time.sleep (Random.randrange (1,5))    Print('welecome to index page') @timmerdefHome (name): Time.sleep (Random.randrange (1,3))    Print('welecome to%s HOME page'%name)return123123123123123123123123123123123123123123res1=index ()Print('Index return%s'%res1) Res2=home ('Egon')#Wraper ()Print('Home Return%s'%RES2)

Python Development Basics-day7-closure functions and adorners basics

Related Article

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.