In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use the decorator correctly". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the decorator correctly.
1. A simple definition of decorator
The outer function returns a reference to the inner function, and the inner function refers to the variables of the outer function.
Second, the function of the decorator
Generally speaking, the function of the decorator is to add new functions to the function without changing the existing function code.
Def run (): print ('I can run') fun ()
Now I want to add a function to the original function: I can sing. At this time, the use of decorators can easily help us to achieve this function.
Third, case understanding
(1) decorators that do not transmit parameters
Def outer (fun): def inner (): fun () / / fun is the variable of the outer function. Using return inner / / inner in inner is the reference of the inner function.
(2) the decorator that passes parameters:
Def func (fun): def add (* args,**kwarge): return fun (* args,**kwargs) return add
Now that you have some understanding of the basic format of the decorator, you can write functions directly. Now realize the function that I can sing at the beginning of the article.
Def outer (fun): def inner (* args, * * kwarge): print ("I can sing") return fun (* args, * * kwarge) return inner
Fourth, how to use the decorator
Method 1: use the @ symbol + decorator name to put it on the last line of the function you want to decorate. @ outer def run (): print ('I can run') run () method 2: def run (): print ('I can run') run=outer (run) # is equivalent to @ outer run () the final print result is: I can sing and I can run
If I want to know what parameters are passed by fun, I can use the following methods inside the decorator:
Def outer (fun): a = 1 def inner (* args, * * kwarge): # args is an array, kwargs a dictionary print (fun.__name__) # print the name of the function received by fun print ("I can sing") return fun (* args, * * kwarge) return inner
But if the output of our print (run.__name__,6666666) is inner, which is not the run we want, the function here is replaced by warpTheFunction. It rewrites the name and comment document (docstring) of our function. The solution is as follows:
From functools import wraps def outer (fun): @ wraps (fun) def inner (* args, * * kwargs): print (fun.__name__,11111111111) print ("I can sing") return fun (* args, * * kwargs) return inner @ outer def run (): print ('I can run') print (run.__name__,6666666) / / output is run 666666
Fifth, implement the decorator by yourself.
Def subuser_keymanage (view_func):
The function is to realize the determination of user's administrative authority.
Def _ wrapper_view (request, * args, * * kwargs):
User = request.user # A Customer object that contains information such as user name / password
Customer = user.customer.customer_id # id of the user
Select_status = get_curuser_permission (user=user, customer=customer) # the values returned by the calling function are 0 and 1
If if not select_status:# returns 0, it means there is no permission. An error code is returned.
Return render_response (request, ErrorCode.FAILED)
Return view_func (request, * args, * * kwargs)
Return _ wrapper_view
@ subuser_keymanage def generate_subuser_ak_sk (request): params = json.loads (request.body) # get the parameter user_id_only = params.get ("user_id") passed by the front end of the card. Return render_response (request, ErrorCode.FAILED)
VI. Summary of decorators
The reuse of code can be greatly reduced through decorators, which is important in the code specification.
The above is the basic knowledge of the decorator, even if there is no foundation, according to the author's ideas, apply a fixed format, do not need to fully understand, as long as follow the process step by step to write a high-end atmospheric grade decorator, congratulations!
In front of the high-energy please note: decorator parameters, three-layer nested functions are generally used less, in fact, it is not difficult, layer by layer, as mentioned above, only as a widening of knowledge.
Import logging
Def use_logging (level):
Def decorator (func):
Def wrapper (* args, * * kwargs):
If level = = "warn":
Logging.warn ("s is running" func.__name__)
Elif level = = "info":
Logging.info ("s is running" func.__name__)
Return func (* args)
Return wrapper
Return decorator
@ use_logging (level= "warn")
Def foo (name='foo'):
Print ("I am s" name)
Foo ()
I am foo WARNING:root:foo is running so far, I believe that everyone on "how to correctly use the decorator" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 237
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.