First, the adorner decorator
The decorator design pattern allows you to dynamically wrap existing objects or functions so that you can modify existing responsibilities and behaviors, simply to dynamically extend existing functionality. In fact, the concept of AOP in other languages separates the real functions of objects or functions from other auxiliary functions.
Second, the decorator in Python
The decorator in Python is usually to enter a function, which is decorated to return another function. The more commonly used features are generally implemented using decorator, such as Python's own staticmethod and Classmethod.
There are two forms of adorners:
Copy Code code as follows:
Equivalent:
Copy Code code as follows:
def foo ():
Pass
foo = A (foo)
The second is with parameters:
Copy Code code as follows:
@a (ARG)
def foo ():
Pass
is equivalent to:
Copy Code code as follows:
def foo ():
Pass
Foo = A (arg) (foo)
You can see that the first adorner is a function that returns a function, and the second adorner is a function that returns a function.
Decorator in Python can be used multiple simultaneous, as follows:
Copy Code code as follows:
@a
@B
@c
def f (): Pass
# It is same as below
def f (): Pass
f = A (B (C (f)))
Three, the common decorator example in Python
Decorator is usually used for authorization before execution, logging, or even modifying incoming parameters, or preprocessing the return results after execution, or even truncating the execution of functions, and so on.
Example 1:
Copy Code code as follows:
From Functools Import Wraps
def logged (func):
@wraps (func)
def with_logging (*args, **kwargs):
Print (func.__name__ () + "was called")
return func (*args, **kwargs)
Return with_logging
@logged
def f (x):
"" "Does some Math" "
return x + x * x
Print (f.__name__) # prints ' F '
Print (f.__doc__) # prints ' does some math '
Note the role of the Functools.wraps () function: Call the decorated function, the equivalent of calling a new function, that look at the function parameters, comments, and even function names, you can only see the relevant information of the adorner, the wrapper function information was discarded. and wraps can help you transfer this information, see http://stackoverflow.com/questions/308999/what-does-functools-wraps-do