Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What are the main functions of the Python decorator

Shulou Source: shulou.com Published: 2022-06-02 04:39:04 10月04日 Update

This article mainly introduces "what is the main function of Python decorator". In daily operation, I believe that many people have doubts about the main function of Python decorator. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the question of "what is the main function of Python decorator?" Next, please follow the editor to study!

Python decorator is a function used to expand the function of the original function. The special feature of this function is that its return value is also a function (function pointer). The advantage of using python decorator is to add new functions to the function without changing the code of the original function.

Add code execution time to the current code

Import timedef func (): beginTime = time.time () print ("hello world") time.sleep (2) print ("hello python") endTime = time.time () print (endTime-beginTime) func ()

If you need to increase code execution time in other functions, there is a lot of repetition.

Import timedef foo (): print ("hello world") time.sleep (2) print ("hello python") def decorator (func): beginTime = time.time () func () endTime = time.time () print (endTime-beginTime) if _ name__=='__main__': f = foo decorator (f) # the newly added function takes effect only if func () or f () is executed as a parameter ("

Decorator representation

Import timedef deco (func): def wrapper (): beginTime = time.time () func () endTime = time.time () print (endTime-beginTime) return wrapper@decodef foo (): print ("hello world") time.sleep (2) print ("hello python") if _ name__=='__main__': foo () here The study on "what is the main function of Python decorator" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Functions functions code learning that is time more help practical great special next no premises parameters only benefits pointers articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL macOS vpn Docker Redmi