What ' s the Python function and decorator

Source: Internet
Author: User
Tags closure

What ' s the function?

definition of the function:   (return is the returned value, no, but none if not)

def Wrapper (parameter 1, parameter 2,*args, default parameter, * *Kwargs)    :' Comment: function function and parameter description '          function Body                 return value 

The function is to package the contents of the call into the Def (), read into memory without invoking it, do nothing, and then step through the call.

  parameters of the function: both the physical and the actual parameters, the formal parameter refers to the definition is written in the parentheses after the Def, the actual argument refers to the code that will be used to invoke the real arguments, the formal parameter is in the definition phase to help the real parameter occupied position.

formal parameters: positional parameters, default arguments, dynamic arguments, named keyword parameters

Positional parameters: According to the order from left to right, must be passed value, one more not, one less. (It can be defined as a positional parameter when the value changes frequently)

Default parameters: When the function is defined, the parameter is already assigned a value, the call stage can be used without passing the value (the value is basically the same as the default parameters, the call stage can ignore the non-pass value.) such as the sex of a miner, the birthplace of a student in a rural primary school, etc.). Factors to note: One: must be placed behind the position parameter; Two: default parameters are usually defined as immutable types, and three: default parameters are assigned only once in the definition phase.

Dynamic parameters: The length of the argument is not fixed is the dynamic parameters *args* and *kwargs, can accept any type

Named keyword parameters: The parameter defined in the *, such parameters, must be passed the value, and the truth must be in the form of a keyword to pass values, such as:

def Register (*args,name='Egon', age):    print(args)     Print (name)     Print (age) ## register (name= ' Egon ', age=18)Register (1,2,2,3,age=10)

Formal parameters are defined in the following order : positional parameter, default parameter, *args, named keyword parameter, **kwargs

Arguments : positional arguments, keyword arguments (the positional arguments must precede the keyword arguments)

Positional arguments: Corresponds to positional parameters, collectively referred to as positional arguments

Keyword parameter: The value of the name in the form of key=value, can not be like positional arguments with the parameter one by one corresponding

What ' s the namespace?

namespaces : built-in namespaces, global namespaces, local namespaces

load Order: built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: Load only when called)

The corresponding variables are global variables and local variables, and the order of values for local variables is:

Built-in namespaces, local namespaces, and global namespaces, local calls

Global invocation: Built-in namespaces, global namespaces

function Nesting: defined functions can be re-defined function, internal function is nested into the function, to remember that the general function has return value returned

Scope is the scope of action, according to the effective scope can be divided into global scope and local scope. The scope relationship of a function is fixed in the function definition phase, regardless of where the function is called, and it needs to go back to the definition phase to find the corresponding scope relationship.

Application of nonlocal Keywords:

# 1. External must have this variable
# 2. Variables with the same name can no longer appear before an intrinsic function declares a nonlocal variable
# 3. Internally modify this variable if you want to take effect in the first layer function that has this variable externally
def F1 ():     = 1    def  F2 ():        nonlocal a        = 2    f2 ()    print('  ', a) F1 ()

The essence of a function name is the memory address of the function, which can be referred to as an element of the container type, and can be used as the parameter and return value of the function. Function names can be used as normal variables.

Note:

The first class of objects (first-class object) refers to 1. You can create 2 at run time. Use as a function parameter or return value 3. The entity that can be stored in a variable.

closure function: define a function inside the function that contains a reference to the outer scope, not to the global domain name Word, then the intrinsic function is called the closure function. (The function is closed even if it does not return)

The feature of the closure function is that it is self-contained, that is, the variable that always carries its outer scope, and the same variable that has a different value at the time of the call can not change the value of the variable it carries.

Defines the basic form of a closure function:

def external Function name (): intrinsic function    requires variable def  intrinsic ():        reference external variable     return intrinsic function

Give me a little chestnut:

def func ():# The following indent content is a closure function    name='Alex'    def  Bar ():        print(name)    return  barb=func () # because the Func () return is out of bar, B is equal to barB ()# this B () is bar (), which is a closure function

One way to view the closure function: print (b.__closure__[0].cell_contents) #如果结果是None, which means that it is not a closure function.

B means closure, __closure__ refers to the id,[0 of the variable being carried) refers to the first variable that is carried, and the cell_contents value is the value of the view carrying variable.

One application of the closure function is the adorner, which is born because the code changes follow the open closure principle-the code that has implemented the function cannot be modified, but can be extended. is because can not be modified, so there is an adorner, so as not to modify the source code under the premise of the effect of modification.

The basic form of the adorner :

# Decorative Device def Wrapper (func):     def Inner (*args,**kwargs):# when defining a function--* parameter aggregation        ret = func (*args,**kwargs)  #  when calling a function, the--* parameter of the break        #func is the function that is decorated, RET is the return value of the decorated function         return # Returns the returned value of the decorated function to the caller    return Inner

The method to invoke the adorner is the @ adorner, which is called the syntax sugar, just above the function to be called.

Adorner with switch:

defouter (flag):defTimer (func):defInner (*args,**Kwargs):ifflag:Print(" "what to do before executing a function" ") Re= Func (*args,**Kwargs)ifflag:Print(" "what to do after the function is executed" ")            returnRereturnInnerreturnTimer@outer (False)#the parameter is false to turn off the adorner, true to open#opening the adorner executes the Chinese in the code, which is the part that performs the function that you want to modify the original code with the adorner .deffunc ():Print(111) func ()

A function can be decorated by multiple adorners, and an adorner can decorate several different functions.

When a function is decorated by more than one adorner, the first one is to run the topmost adorner, and here is a little chestnut:

defWrapper1 (func):definner ():Print('Wrapper1, before Func') func ()Print('Wrapper1, after Func')    returnInnerdefWrapper2 (func):definner ():Print('Wrapper2, before Func') func ()Print('Wrapper2, after Func')    returnInner@wrapper2#The adorner decorates the decorated function, so for this adorner the following is a function, that is, the order in which the topmost adorner runs first@wrapper1#adorner decorated with F ()deff ():Print('In F') F ()" "print results for Wrapper2, before Funcwrapper1, before Funcin Fwrapper1, after Funcwrapper2, after Func" "

What ' s the Python function and decorator

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.