The learning journey of Python ——— function objects, function nesting, namespaces and scopes, adorners

Source: Internet
Author: User
Tags closure ldap

A Function object

1 can be referenced

2 can be passed as a parameter

3 The return value can be a function

4 elements that can be used as container types

1 def foo (): 2     Print ('fromfoo') 3  4 func=foo5  6print(foo)7  Print(func)8 func ()

Namespace: Where the name is stored, the exact name space is where the name and the value of the variable are bound.

One, the name space is divided into:

Built-in namespaces: generated when the Python interpreter starts, storing some python built-in names

Global namespaces: Generated when a file is executed, holding the name of a file-level definition

Local namespaces: In the process of executing a file, if a function is called, the local namespace of the function is generated
Used to hold the name defined within the function, which takes effect when the function is called and expires after the function call ends

Second, load order

Load order: Built-in---> Global---> Local

Third, the name of the search order

Local-to-global built-in

Iv. Scope

Definition: Scope of the action

One, divided into

Global scope: Global survival, globally valid: can be viewed with globals ()

Local scope: Temporary survival, local effective can be viewed with locals ()

Second, change the global variables

1. Global variables can be changed locally

Declaring a global variable, if you want to modify the global variable locally, you need to declare the global variable locally as well:

2. variable variable can not be modified in function by global

L=[]def F2 ():    l.append (' F2 ') F2 () print (L)

3., nonlocal keyword used to use outer (non-global) variables in functions or other scopes

Three, the scope relationship

When a function is defined, it is fixed to the call location regardless, and when the function is called, it must go back to the location where the function was originally defined to find the scope relationship

LEGB representative name Lookup order: Locals, enclosing function, globals, __builtins__

Locals are namespaces within functions, including local variables and formal parameters

enclosing namespaces for outer nested functions (common in closures)

Globals global variables, the namespace of the module in which the function is defined

Builtins the namespace of the built-in module

Four-closed packet function

Intrinsic functions contain references to external scopes rather than global scopes.

The closure function is based on the argument that the corresponding value of the variable is not found inside the function, it will look up in the first-level function.

The value of the variable.

The significance and application of two-closure package

Prepare for the decorator (I think so)

Five Decorators

The utensil of another person can be any callable object, and the adorner can be any callable object.

The principle of emphasizing adorners:

1 Do not modify the source code of the object being decorated

2 Do not modify the calling method of the decorated object

Object of the adorner: Add new features to the adorned object, following the 1 and 2 prerequisites

The principle of adorners: without modifying the function invocation method and the function itself code. Add new features open closure principle, open for expansion, and closed for modification.

Non-parametric adorner

1 Import Time2 3 defTimmer (func):4     #Func=index #最原始的index函数的内存地址5     definner ():6Start_time=time.time ()7 func ()8Stop_time=time.time ()9         Print('run time is: [%s]'% (stop_time-start_time))Ten     returnInner One  A@timmer#Index=timmer (Index) - defindex (): -Time.sleep (3) the     Print('Welcome to Index page') -Index ()

There are a few key code in execution to @timmer do two things 1 will index () function name ' index ' passed to Timmer so there is Timmer (index), 2 will Timmer () assigned to index, (in Python, variable name can be reused, This kind of operation I think is sipilailian to do the same purpose of the Call Method Index=timmer ()

Timmer is a closure function, so there is a 4 # Func=index #最原始的index函数的内存地址 because of the characteristics of the closure function, so inner in the internal function func () when looking for the Func value will be looking up a layer

So he found the func=index. The inner () inner function func () becomes index (), and the inner function finally return itself to Timmer ()

At this point index=timmer () is actually =inner at this time @timmer task is completed, the code jumps directly to 16 lines to index () at this time index () ==inner ().

The next sequence is 5-6-7-14-15-8-9.

Decorator Revision

1 Import Time2  fromFunctoolsImportWraps3 4 defTimmer (func):5 @wraps (func) #help等功能6     defInner (*args,**Kwargs):7Start_time=time.time ()8Res=func (*args,**Kwargs)9Stop_time=time.time ()Ten         Print('run time is: [%s]'% (stop_time-start_time)) One         returnRes A  -     returnInner - @timmer the defindex (): -     " " - Index function - : return: +     " " -Time.sleep (3) +     Print('Welcome to Index page') A     return123 at  -@timmer#Home=timmer (Home) #home =inner - defHome (name): -Time.sleep (2) -     Print('Welcome%s to home page'%name) -     return456

With reference decorator

1 Import Time2current_status={'User': None,'Login_status': False}3 defAuth (egine='file'):4     #egine= ' file '5     defWrapper (func):6         defInner (*args,**Kwargs):7             ifcurrent_status['User'] andcurrent_status['Login_status']:8res = func (*args, * *Kwargs)9                 returnResTen  One             ifEgine = ='file': Au='Egon' -p='123' -             elifEgine = ='MySQL': the                 Print('MySQL Auth') -U ='Egon' -p ='123' -             elifEgine = ='LDAP': +                 Print('LDAP Auth') -             Else: +                 Pass AName = input ('Username>>:'). Strip () atPWD = input ('Password>>:'). Strip () -             ifname = = U andPWD = =P: -                 Print('Login Successfull') -current_status['User'] =name -current_status['Login_status'] =True -res = func (*args, * *Kwargs) in                 returnRes -         returnInner to     returnwrapper +@auth (egine='LDAP')#@wrapper #index =wrapper (index) #index =inner - defindex (): theTime.sleep (3) *     Print('Welcome to Index page') $     return123

Wrapper is a non-parametric adorner, now wrapper internal needs parameters Egine, so we need to find a way to egine, then we use the closure function. Wrapper outside to package a parameter, so there is auth (egine), decoration will be written as

@auth (Egine) The above code is written @auth (egine= ' file '), just giving a default initial value. When running code, see @auth (egine= ' file ') First forget that he is the decorator first execute auth (egine= ' file ') The function then gets the return out of the wrapper and then has the @wrapper which is our no-parameter decorator.

Therefore, the essence of the parametric adorner is the closure function of the non-parametric adorner. The adorner is three levels long enough.

Adorners are ordered. Decorate the following code (if there are more adorners below).

There is a three-storey decorative decorator

1 outer-layer communication to internal core functions

2 middle-level function does not change the way the decorated function is called

3 The core layer is the internal functional layer

The learning journey of Python ——— function objects, function nesting, namespaces and scopes, adorners

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.