Python Adorner "Go"

Source: Internet
Author: User
Tags call back closure

Related

function Scope Legb:l>e>g>b

  • l:local function Internal Scope
  • E:enclosing between inside and inline functions (closures)
  • G:global Global scope
  • B:build-in built-in scopes

closure Closure Concept : The internal function Squadron enclosing the variable of the scope, put the variable into the closure property, and when the internal function is processed, you can use the variable directly.

function Essence and property

  1. A function is an object
  2. Internal variable recycling after function execution completes
  3. function properties
  4. function return value

Closure effect : 1. Encapsulation 2. Code reuse

Decorative Device

The decorator is actually a syntactic sugar brought by the closure.

Decorative Device

Because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.

>>> from time import ctime>>> def now():...     return ctime()... >>> f = now>>> f()'Sat Feb 24 16:43:28 2018'

A function object has a __name__ property that can get the name of the function:

>>> now.__name__'now'>>> f.__name__'now'

Now, suppose we want to enhance now() the function of functions, for example, to automatically print the log before and after a function call, but do not want to modify the definition of the now() function, this way of dynamically adding functionality during the run of the code, called "Adorner" (Decorator).

Essentially, decorator is a higher-order function that returns a function. So, we want to define a decorator that can print the log, which can be defined as follows:

>>> def log(func):...     def wrapper(*args, **kw):...         print('call %s():' % func.__name__)...         return func(*args, **kw)...     return wrapper

Observe the above log , because it is a decorator, so accept a function as an argument and return a function. We will use the Python @ syntax to place the decorator at the definition of the function:

@logdef now():    print '2013-12-25'

Calling now() a function will not only run the now() function itself, but will also now() print a line of logs before running the function:

>>> @log... def now():...     print(ctime())...     ... >>> now()call now():Sat Feb 24 16:47:53 2018

Put @log to now() the definition of the function, the equivalent of executing a statement:

now = log(now)

Since log() it is a decorator that returns a function, the original now() function still exists, but the now variable with the same name points to the new function, and the call now() executes the new function, which is the log() function returned in the function wrapper() .

wrapper()The function's parameter definition is (*args, **kw) , therefore, the wrapper() function can accept calls of arbitrary arguments. wrapper()inside the function, the log is printed first and then the original function is called.

If the decorator itself needs to pass in parameters, it is necessary to write a higher-order function that returns decorator, which is more complex to write. For example, to customize the text of a log:

def log(text):    def decorator(func):        def wrapper(*args, **kw):            print '%s %s():' % (text, func.__name__)            return func(*args, **kw)        return wrapper    return decorator

This 3-level nested decorator usage is as follows:

@log('execute')def now():    print '2013-12-25'

The results of the implementation are as follows:

>>> now()execute now():2013-12-25

Compared to the two-layer nested decorator, the 3-layer nesting effect is this:

>>> now = log('execute')(now)

Let's parse the above statement, execute it first, log(‘execute‘) return the decorator function, call back the function, the argument is the now function, the return value is the wrapper function.

There is no problem with the definitions of the two decorator, but the last step is not the case. Because we're talking about functions and objects, and it has __name__ properties like that, but you see the functions after the decorator decoration, and they __name__ have changed from the original ‘now‘ ‘wrapper‘ :

>>> now.__name__'wrapper'

Because the name of the function returned is the same, wrapper() ‘wrapper‘ so you need to copy the properties of the original function __name__ into the wrapper() function, otherwise, some code that relies on the function signature will be executed with an error.

There is no need to write wrapper.__name__ = func.__name__ such code, Python functools.wraps is built to do this, so a complete decorator is written as follows:

import functoolsdef log(func):    @functools.wraps(func)    def wrapper(*args, **kw):        print 'call %s():' % func.__name__        return func(*args, **kw)    return wrapper

or for decorator with parameters:

import functoolsdef log(text):    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kw):            print '%s %s():' % (text, func.__name__)            return func(*args, **kw)        return wrapper    return decorator

import functoolsis the import functools module. The concept of the module is explained later. Now, just remember to add it to the wrapper() front of the definition @functools.wraps(func) .

In the object-oriented (OOP) design pattern, the decorator is called the adornment mode. The Deco pattern of OOP needs to be implemented through inheritance and composition, while Python supports decorator directly from the syntax level, in addition to the decorator of OOP. Python's decorator can be implemented using functions or classes.

Decorator can enhance the function of functions, although the definition is a bit complex, but it is very flexible and convenient to use.

Write a decorator that can print out and back the log before and after the function call ‘begin call‘ ‘end call‘ .

Think again about whether you can write a @log decorator that supports both:

@logdef f():    pass

also supports:

@log('execute')def f():    pass
Partial function

The Python functools module provides a number of useful functions, one of which is the partial function. It is important to note that the partial function here is not the same as the partial function in mathematical sense.

When we introduce the function parameters, we can reduce the difficulty of the function call by setting the default value of the parameter. The partial function can do this, too. Examples are as follows:

int()Functions can convert a string to an integer, and when passed in only the string, the int() function defaults to decimal conversion:

>>> int('12345')12345

But int() the function also provides additional base parameters, the default value is 10 . If you pass in base a parameter, you can do an n-binary conversion:

>>> int('12345', base=8)5349>>> int('12345', 16)74565

Assuming that you want to convert a large number of binary strings, each time it is very troublesome to pass in, int(x, base=2) so, we think, can define a int2() function, the default is base=2 passed in:

def int2(x, base=2):    return int(x, base)

In this way, it is very convenient for us to convert the binary:

>>> int2('1000000')64>>> int2('1010101')85

functools.partialis to help us create a biased function, without our own definition int2() , you can create a new function directly using the following code int2 :

>>> import functools>>> int2 = functools.partial(int, base=2)>>> int2('1000000')64>>> int2('1010101')85

So, the simple summary functools.partial of the function is to put some parameters of a function fixed (that is, set the default), return a new function, call this new function is more simple.

Notice that the new function above int2 simply base sets the parameter back to the default value 2 , but can also pass in other values when the function is called:

>>> int2('1000000', base=10)1000000

Finally, when you create a partial function, you can actually receive the function object, *args and **kw These 3 parameters, when passed in:

int2 = functools.partial(int, base=2)

The key parameter of the int () function is actually fixed base , i.e.:

int2('10010')

Equivalent:

kw = { base: 2 }int('10010', **kw)

When incoming:

max2 = functools.partial(max, 10)

Will actually 10 *args add the part automatically to the left, namely:

max2(5, 6, 7)

Equivalent:

args = (10, 5, 6, 7)max(*args)

The result is 10 .

Reference

From the course of Mu-Net tutorial notes

Python Adorner "Go"

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.