the decorator.
Simple decorator
Def use_logging (func): def wrapper (): logging. warn ("% s is running" % func. _ name _) return func () # When passing foo as a parameter, executing func () is equivalent to executing foo () return wrapperdef foo (): print ('I am Foo') foo = use_logging (foo) # The function object wrapper returned by the decorator use_logging (foo). This statement is equivalent to foo = wrapperfoo () # executing foo () is equivalent to executing wrapper ()
Use_logging is a decor
before executing a_func ()# I AM the another function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func ()Here @a_new_decorator is equivalent to A_new_decorator (b_function_requiring_decoration)6) Get NameFor the a_function_requiring_decoration in 4, we printed print (a_function_requiring_decoration.__name__) to get the result wrapthefunction , and what we actually want to get is the name of the A_function_requiring_decoration function that
One: Internal insert1:append: Appends content to each matching element.$("p").append("2:appendto (content): Appends all matching elements to another specified set of element elements.$("p").appendTo("div");3:prepend (content): The contents of the predecessor to each matched element.$("p").prepend("4:prependto (content): puts all matching elements in front of another, specified set of element elements.$("p").prependTo("#foo");Two: External insertion1:after (content): Inserts the contents after ea
functions with hope, for example, to decorate B with aJust on the line that defines the B function, write the @A
def A(): pass @A def B(): pass
Summary: Understanding is the decorator is actually a function of a parameter, and the parameter is a function of another functionThe purpose of using adorners is generally to change some properties/behaviors of a function at run time, you can add an adorner to the function, let the decorator go before and after the funct
function:Import functoolsdef Log (func): @functools. Wraps (func) def wrapper (*args, **kw): print "Call%s:"%func.__ name__ return func (*args, **kw) return wrapperThe wraps function can be implemented using the module FUNCTOOLS.The above describes the decorator pattern, the following gives a more complete example.#!/usr/bin/env pythonimport sys#decoratorimport functoolsdef log (func
Python Functools.wraps Instance Interpretation1. Instances where wraps are not used#!/usr/bin/env python#Coding:utf-8deflogged (func):defWith_logging (*args, * *Kwargs):" "I am wraps ' s doc" " PrintFunc.__name__+"was called" returnFunc (*args, * *Kwargs)returnwith_logging@loggeddeff (x):"""I am original Doc""" returnx + x *xPrintF.__NAME__ # expects the original name F, and the result is r
settings, and the AllowUpdate attribute can control NoFieldUpdate and NoNewFields. If necessary, you can also use public fields to modify the original parameters more precisely. [Vb] % REM Class DialogBox Description: Wraps the ws. dialogbox () method. % end rem Public Class DialogBox Public FormName As String Public HorizonalFit As Boolean Public VerticalFit As Boolean Public NoCancel As Boolean Public NoNewFields As Boolean Public NoFieldUpdate As
) inserts content after each matching element.Description:Insert HTML code after all paragraphs.HTML code:Jquery code:$ ("P"). After ("Result:
(2) Before () insert content before each Matching ElementDescription:Insert HTML code before all paragraphs.HTML code:Jquery code:$ ("P"). Before ("Result:[(3) insertafter inserts all matching elements to the end of another specified Element Set.Description:Insert all paragraphs into one element. Same as $ ("# foo"). After ("p ")HTML code:Jquery code:$ (
#
It is same as below
Def F ():
Pass
F = A (B (C (F )))
Iii. Common decorator instances in Python
Decorator is usually usedPerform permission authentication, logging, modifying input parameters, preprocessing of returned results, and even truncation of function execution before execution.
Instance 1:
From Functools
Import Wraps
Def Logged (func ):
@ Wraps (func)
Def With_log
to see my blog at the beginning of the blog linkSo in the APIView class, what do we focus on return csrf_exempt(view) ?def csrf_exempt (view_func): def Wrapped_view (*args, * *Kwargs) :return view_func (*args, * *Kwargs) = True return wraps (View_func, Assigned=available_attrs (View_func)) (Wrapped_view )wrapped_view.csrf_exempt = TrueThis means canceling the current function of anti-cross-site request forgery, even if the global m
document. You can solve this problem through functools. wraps. Wraps is decorated by a function, and supports copying function names, commenting documents, parameter lists, and other functions. This allows us to access the attributes of the function before decoration in the decorator.
More standardized writing:
from functools import wrapsdef decorator(func): @wraps
method with the parameterized decorator! I can even choose whether to allow GET and POST, or only one request parameter type.
@post_only@json_response@parameterize_request(["POST"])def register(request, username, email, password, first_name=None, last_name=None): user = User.objects.create_user(username, email, password) user.first_name=first_name user.last_name=last_name user.save() return {"success": True}
Now we have a simple and easy-to-understand api.
BONUS #2: Use functools.
content after each matching element.Description:Insert HTML code after all paragraphs.HTML code:JQuery code:$ ("P"). after ("Result:(2) before () insert content before each Matching ElementDescription:Insert HTML code before all paragraphs.HTML code:JQuery code:$ ("P"). before ("Result:[(3) insertafter inserts all matching elements to the end of another specified Element Set.Description:Insert all paragraphs into one element. Same as $ ("# foo"). after ("p ")HTML code:JQuery code:$ ("P"). inser
answer is the decorator.Simple decorator
Def use_logging (func): def wrapper (): logging. warn ("% s is running" % func. _ name _) return func () # When passing foo as a parameter, executing func () is equivalent to executing foo () return wrapperdef foo (): print ('I am foo') foo = use_logging (foo) # The function object wrapper returned by the decorator use_logging (foo). This statement is equivalent to foo = wrapperfoo () # executing foo () is equivalent to executing wrapper ()
Use_logging i
passing foo as a parameter, executing func () is equivalent to executing foo () return wrapperdef foo (): print ('I am foo') foo = use_logging (foo) # The function object wrapper returned by the decorator use_logging (foo). This statement is equivalent to foo = wrapperfoo () # executing foo () is equivalent to executing wrapper ()
Use_logging is a decorator. It is a common function that wraps func, which executes the real business logic. It looks lik
Today, I accidentally saw the Functools module in Python, found that the use of this module wraps () can implement some functions like interceptors, such as: packaging exceptions, hidden exceptions, print logs, statistical function use time. Here is a few pieces of code to see how to use the specific:
Wrapper exception#!/usr/bin/env python#-*-Coding:utf-8-*-Import Functools
def wrap_exception (func):@functools.
new function, and calling‘‘‘#decorator本身需要传入参数.def log (text):def decorator (func):def wrapper (*args,**kwargs):Print ('%s%s (): '% (text,func.__name__))Func (*args,**kwargs)Return wrapperreturn decorator@log (' Execute ')def now ():Print (' 2018-07-15 ')Now ()# "Parse" equivalent to define now = log (' Execute ') (now)#经过decorator装饰的函数, the name will be programmed wrapper, in order to avoid the code execution error since the function signed, do not need to write wrapper.__name__ = func.__name_
elements (1) after (content) inserts the content after each matching element.Describe:Insert some HTML tag code after all the paragraphs.HTML Code:JQuery Code:$ ("P"). After ("Results:(2) before () inserts the content before each matching elementDescribe:Inserts some HTML markup code before all the paragraphs.HTML Code:JQuery Code:$ ("P"). Before ("Results:[(3) InsertAfter inserts all matching elements behind another, specified set of element elements.Describe:Inserts all the paragraphs behind
import decorator def check (flag): @decorator def check_num (func, *args, **kwargs): if Flag = = ' false ': print ' skip check! ' return func (*args,**kwargs) if Len (args)! = 2: raise Exception (' Your args number is not ') else: return func (*args, **kwargs) return check_num @check (' false ') def add (x, y): return x + y >>>add
Decorator module Here, this module is relatively simple, there are some features do
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.