In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article Xiaobian introduces in detail for you "how to create and use Python decorator", the content is detailed, the steps are clear, and the details are handled properly. I hope this "how to create and use Python decorator" article can help you solve your doubts.
When to use the decorator in Python
You will use the decorator when you need to change the behavior of the function without modifying the function itself. Some good examples are when you want to add logging, test performance, execute caching, verify permissions, and so on.
You can also use decorators when you need to run the same code on multiple functions. This prevents you from writing repetitive code.
The following is the building block used to create the Python decorator
To better understand how decorators work, you should first understand some concepts.
A function is an object. Therefore, functions can be assigned to variables. You can access the function from this variable.
Def my_function (): print ('I am a function.') # Assign the function to a variable without parenthesis. We don't want to execute the function.description = my_function# Accessing the function from the variable I assigned it to.print (description ()) # Output'I am a function.'
two。 One function can be nested within another.
Def outer_function (): def inner_function (): print ('I came from the inner function.') # Executing the inner function inside the outer function. Inner_function () outer_function () # OutputI came from the inner function.
Please note that inner_function is inside outer_function. If I try to execute inner_function external, outer_function I will receive a NameError exception.
Inner_function () Traceback (most recent call last): File "/ tmp/my_script.py", line 9, in inner_function () NameError: name 'inner_function' is not defined
3. Because a function can be nested within another function, it can also be returned.
Def outer_function ():''Assign task to student''' task =' Read Python book chapter 3.' Def inner_function (): print (task) return inner_functionhomework = outer_function () homework () # Output'Read Python book chapter 5.'
4. One function can be passed as an argument to another function.
Def friendly_reminder (func):''Reminder for husband''' func () print (' Don\'t forget to bring your walletins') def action (): print ('I am going to the store buy you something nice.') # Calling the friendly_reminder function with the action function used as an argument.friendly_reminder (action) # OutputI am going to the store buy you something nice.Don't forget to bring your wallet! How to create a Python decorator
To create a decorator function in Python, I created an external function that takes the function as an argument. There is also an internal function that surrounds the decorating function.
The following is the syntax of the basic Python decorator:
Def my_decorator_func (func): def wrapper_func (): # Do something before the function. Func () # Do something after the function. Return wrapper_func
To use the decorator, you can attach it to a function, as you can see in the following code. We use the decorator by placing the name of the decorator directly above the function we want to use it. You prefix the decorator function with an @ symbol.
@ my_decorator_funcdef my_func (): pass
This is a simple example. This decorator records the date and time when the function was executed:
From datetime import datetimedef log_datetime (func):''Log the date and time of a function''' def wrapper (): print (f'Function: {func.__name__}\ nRun on: {datetime.today () .strftime ("% Y-%m-%d% H:%M:%S")}') print (f'{"-" * 30}') func () return wrapper@log _ datetimedef daily_backup (): print ('Daily backup job has finished.') Daily_backup () # OutputDaily backup job has finished.Function: daily_backupRun on: 2021-06-06 06Parameters in Python how to add parameters to decorator
The decorator can pass parameters to them. To add parameters to the decorator, I add * args and * * kwargs to the internal function.
* any type of parameter taken by args, the data type is not restricted, such as 10immediate True, or 'Brandon'.
* * kwargs takes any type of keyword parameter, such as count=99, is_authenticated=True, or name='Brandon'.
This is a decorator with parameters:
Def my_decorator_func (func): def wrapper_func (* args, * kwargs): # Do something before the function. Func (* args, * * kwargs) # Do something after the function. Return wrapper_func@my_decorator_funcdef my_func (my_arg):''Example docstring for function''' pass
Decorators hide the functions they are decorating. If I check the _ _ name__or__doc__ method, we get an unexpected result.
Print (my_func.__name__) print (my_func.__doc__) # Outputwrapper_funcNone
To solve this problem, I will use functools. The Functools wrapper updates the decorator with the decorator function property.
From functools import wrapsdef my_decorator_func (func): @ wraps (func) def wrapper_func (* args, * * kwargs): func (* args, * * kwargs) return wrapper_func@my_decorator_funcdef my_func (my_args):''Example docstring for function''' pass
Now I have received the output I expected.
Print (my_func.__name__) print (my_func.__doc__) # Outputmy_funcExample docstring for function running Python decorator example
I created a decorator to measure the memory and speed of the function. We will use the decorator to test performance list generation in four ways: scope, list understanding, append, and join.
From functools import wrapsimport tracemallocfrom time import perf_counter def measure_performance (func):''Measure performance of a function''' @ wraps (func) def wrapper (* args, * * kwargs): tracemalloc.start () start_time = perf_counter () func (* args, * * kwargs) current Peak = tracemalloc.get_traced_memory () finish_time = perf_counter () print (f'Function: {func.__name__}') print (f'Method: {func.__doc__}') print (f'Memory usage:\ t\ t {current / 10mm 6pur.6f} MB\ n 'f'Peak memory usage:\ t {peak / 10mm 6 : .6f} MB') print (f'Time elapsed is seconds: {finish_time-start_time:.6f}') print (f'{"-" * 40}') tracemalloc.stop () return wrapper@measure_performancedef make_list1 ():''Range''' my_list = list (range (100000)) @ measure_performancedef make_list2 ():' 'List comprehension''' my _ list = [l for l in range (100000)] @ measure_performancedef make_list3 ():''Append''' my_list = [] for item in range (100000): my_list.append (item) @ measure_performancedef make_list4 ():' 'Concatenation''' my_list = [] for item in range (100000): my_list = my_list + [item] print (make_list1 ( ) print (make_list2 ()) print (make_list3 ()) print (make_list4 ()) # OutputFunction: make_list1Method: RangeMemory usage: 0.000072 MB Peak memory usage: 3.693040 MB Time elapsed is seconds: 0.049359--Function: make_list2Method : List comprehensionMemory usage: 0.000856 MB Peak memory usage: 3.618244 MB Time elapsed is seconds: 0.052338--Function: make_list3Method: AppendMemory usage: 0.000448 MB Peak memory usage: 3. 617692 MB Time elapsed is seconds: 0.060719--Function: make_list4Method: ConcatenationMemory usage: 0.000440 MB Peak memory usage: 4.393292 MB Time elapsed is seconds: 61.649138- -
You can also use decorators with classes. Let's look at how to use the decorator in the Python class.
In this example, notice that @ does not involve any characters. Using the _ _ call__ method, the decorator is executed when an instance of the class is created.
This class tracks the number of times the function that queried API has been run. Once the limit is reached, the decorator stops executing the function.
Import requestsclass LimitQuery: def _ init__ (self, func): self.func = func self.count = 0 def _ call__ (self, * args, * * kwargs): self.limit = args [0] if self.count < self.limit: self.count + = 1 return self.func (* args, * * kwargs) else: print (f'No queries left. All {self.count} queries used.') Return@LimitQuerydef get_coin_price (limit):''View the Bitcoin Price Index (BPI)' 'url = requests.get (' https://api.coindesk.com/v1/bpi/currentprice.json') if url.status_code = = 200: text = url.json () return f "${float (text ['bpi'] [' USD'] ['rate_float']): .2f}" print (get_coin) _ price (5) print (get_coin_price (5)) # Output$35968.25 $35896.55 $34368.14 $35962.27 $34058.26No queries left All 5 queries used.
This class will track the state of the class.
Read here, this article "how to create and use Python decorator" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.
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: 0
*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.