Python Adorner Decorator Usage example

Source: Internet
Author: User
This example describes the Python adorner decorator usage. Share to everyone for your reference. The specific analysis is as follows:

1. Closures (closure)

A closure is a feature supported by Python that allows a function defined in a non-global scope to reference a variable in its outer space, which is referred to as the environment variable of the function. The environment variable and this non-global function together form the closure.
Copy the Code code as follows:

def outer (x):
y = [x-i]
def inner ():
Print X
Print Y
return inner
x = 5 #这个x没有被引用
f = Outer (2)
F ()


Print f.__closure__ #函数属性__closure__存储了函数的环境变量 def entrance (func):
= 5 #这个x没有被引用f = outer (2) f () print f.__closure__ #函数属性__closure__存储了函数的环境变量 def entrance (func):
X and Y are all part of the function outer namespace, referenced in inner, when the outer function exits, the outer namespace does not exist, but inner still maintains its definition of the connection to its external variable x, Y.
Program output:
2
[1, 2, 3]
(, )

The adorner is a callable object (a callable), in Python, the function is an object and of course it is callable, so the adorner can be a function, which we call a function decorator.
The callable object takes a function as a parameter, closes and returns another function (to replace the function of the parameter).
Like what:

Copy the Code code as follows:

def entrance (func):
def inner ():
Print "Inside function:", func.__name__
Func ()
return inner



Entrance is an adorner, which is a function that can receive a function func as a parameter, returning another function inner.
That's why it's called a decorator, and in the back of the function inner (), the Func () is called, and the extra action is the equivalent of "decorating" the function func.
So how do you use adorners?

Copy the Code code as follows:

Def fun1 ():
Pass
FUN1 = entrance (FUN1)
Def fun2 ():
Pass
fun2 = entrance (fun2)



FUN1,FUN2 's name has not changed, but by calling the function adorner entrance (), they have pointed to another function inner (), "decorate" themselves.

@ operator

The @ symbol provided by Python is essentially what is done above, and the new assignment of a function name is a grammatical technique. So the above code is equivalent to
Copy the Code code as follows:

@entrance
Def fun1 ():
Pass
@entrance
Def fun2 ():
Pass



2. Use of adorners

From this deliberately constructed very simple example, you can see the meaning of the adorner, if a function requires a function, if the function can be used in many functions, or the function is not implemented by itself, it can write an adorner to implement these functions.
The above adorner entrance, after decorating a function, will print out the function's name when it is called.
But there is a problem with this decorator from a functional point of view, is to be able to decorate any function, but if we use it to decorate a function with parameters
Copy the Code code as follows:

@entrance
def fun3 (x):
Pass


As long as you do not call Fun3, these three lines of code will not let the Python interpreter error, because we already know that it is equivalent to:
Copy CodeThe code is as follows:

def fun3 (x):
Pass
FUN3 = entrance (FUN3)



We define a function fun3 with a parameter, and then point fun3 to another function inner (), of course there is nothing wrong with it.

However, when we use FUN3, we will definitely use it as it is defined, passing it a parameter.
>>>FUN3 (1)
There's going to be a mistake here, look at the interpreter.

Traceback (most recent):
File "decorator.py", line at Www.jb51.net
FUN3 (1)
Typeerror:inner () takes no arguments (1 given)

Of course we have been very easy to know why this error, FUN3 has not pointed to its definition of the function, it now points to "inner ()", and inner is no parameter, of course, will be wrong.
How to solve it?
Modify the definition of inner () so that it can take any parameter on it.

Copy the Code code as follows:

def entrance (func):
def inner (*args, **kvargs):
Print "Inside function:", func.__name__
Func (*args, **kvargs)
return inner


Now, it is not an error to pass any parameters to inner, which means that entrance can be used to decorate any function.

3. Write a decorator Logger

When a function is called, its name and the actual parameters invoked are recorded in the log.
Copy the Code code as follows:

def logger (func):
def inner (*args, **kvargs):
Print func.__name__, ' called, arguments: ', args, Kvargs
Func (*args, **kvargs)
return inner

Hopefully this article will help you with Python programming.

  • 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.