Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Python functional programming Decoration

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article shares with you the content of the sample analysis of Python functional programming decorators. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

First, the nature of the decorator:

The decorator is essentially the syntactic Syntactic sugar of the function closure (function closure).

Function closure (function closure):

Function closure is a term in a functional language (a function is a first-class citizen and can be used as a variable). Function closure: a function whose arguments and return values are functions, used to enhance function functionality, aspect-oriented programming (AOP)

Import time# console prints odd numbers within 100: def print_odd (): for i in range (100): if I% 2 = = 1: print (I) # function closure: used to enhance the function func: add statistical time to the function func: def count_time_wrapper (func): def improved_func (): start_time = time.time () func () end_time = time.time () print (f "It takes {end_time-start_time} S to find all the odds in range!!") Return improved_funcif _ _ name__ = ='_ _ main__': # call the count_time_wrapper enhancement function print_odd = count_time_wrapper (print_odd) print_odd ()

The closure is essentially a function, the incoming parameters and return values of the closure function are functions, and the return value function obtained by the closure function is the result of the enhancement of the incoming function.

Log decorator:

Def log_wrapper (func): "closure, used to enhance the function func: add logging function to func" def improved_func (): start_time = time.strftime ('% Y-%m-%d% HGV% MVR% S' " Time.localtime (time.time ()) # start time func () # execute function end_time = time.strftime ('% Y-%m-%d% HV% MVO% Swatch, time.localtime (time.time () # end time print ("Logging: func: {} runs from {} to {}" .format (func.__name__, start_time) End_time) return improved_ function II. How to use the decorator:

Function enhancement through decorators is just a syntactic candy that is essentially the same as the previous program (using function closures).

Import time# function closure: used to enhance the function func: add statistical time to the function func: def count_time_wrapper (func): def improved_func (): start_time = time.time () func () end_time = time.time () print (f "It takes {end_time-start_time} S to find all the odds in range!!") Return improved_func# console prints odd numbers within 100s: @ count_time_wrapper # add decorator def print_odd (): for i in range (100): if I% 2 = = 1: print (I) if _ _ name__ = ='_ main__': # use @ decorator (enhancement function name) to add decorator to the current function It is equivalent to executing the following statement: # print_odd = count_time_wrapper (print_odd) print_odd ()

The decorator is enhanced only once when the decorated function is called for the first time, and the next call is still a call to the enhanced function, and the enhancement is not repeated!

Function closures that retain function parameters and return values:

The previously written function closure does not retain the parameter list and return values of the original main function when enhancing the main function.

A function closure that retains the parameter list and return values:

Def general_wrapper (func): def improved_func (* args, * * kwargs): # enhanced function: ret = func (* args, * * kwargs) # enhanced function: return ret return improved_func

Optimize the decorator (parameter passing, setting return value):

Import time# function closure: used to enhance the function func: add statistical time to the function func: def count_time_wrapper (func): # enhanced function: def improved_func (* args, * * kwargs): start_time = time.time () result = func (* args * * kwargs) end_time = time.time () print (f "It takes {end_time-start_time} S to find all the odds in range!!") # return value of the original function return result return improved_func# calculates the sum of 0-lim odd numbers: @ count_time_wrapperdef count_odds (lim): cnt = 0 for i in range (lim): if I% 2 = 1: cnt = cnt + i return cntif _ _ name__ ='_ _ main__': result = count_odds (10000000) print (f "the result is {result}!") 3. The execution order of multiple decorators: # decorator 1:def wrapper1 (func1): print ("set func1") # outputs def improved_func1 (* args, * * kwargs): print ("call func1") when wrapper1 decorates the function, and outputs func1 (* args) when the wrapper1 decorated function is called * * kwargs) return None return improved_func1# decorator 2:def wrapper2 (func2): print ("set func2") # outputs def improved_func2 (* args, * * kwargs): print ("call func1") # when the wrapper2 decorated function is called (* func2 (* args) * * kwargs) return None return improved_func2@wrapper1@wrapper2def original_func (): passif _ _ name__ = ='_ main__': original_func () print ("-") original_func ()

The execution result here is that the wrapper2 decorator executes first because the program executes from top to bottom when it runs to:

@ wrapper1@wrapper2def original_func (): pass

In this code, the function closure is used to parse to:

Original_func = wrapper1 (wrapper2 (original_func))

So first carry on the wrapper2 decoration, and then decorate the enhancement function completed by wrapper2, and then decorate by wrapper1, and return the final enhancement function.

Create a decorator with parameters:

The decorator allows parameters to be passed in, and a decorator with parameters will have three layers of functions, as follows:

Import functoolsdef log_with_param (text): def decorator (func): @ functools.wraps (func) def wrapper (* args, * * kwargs): print ('call% s ():'% func.__name__) print ('args = {}'. Format (* args)) print ('log_param = {}' .format (text)) return func (* args) * * kwargs) return wrapper return decorator@log_with_param ("paramedics!") def test_with_param (p): print (test_with_param.__name__) if _ _ name__ ='_ _ main__': test_with_param ("test")

Remove the @ syntax and restore the form of the function call:

# pass in the parameters of the decorator and receive the returned decorator function decorator = log_with_param ("paramedical parameters!") # pass in the test_with_param function wrapper = decorator (test_with_param) # call the decorator function wrapper ("I'm a param") Thank you for reading! On the "Python functional programming decorator example analysis" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report