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

What is the common way to create Python decorator

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

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "what is the common way to create Python decorator". In daily operation, I believe that many people have doubts about what is the common way to create Python decorator. The editor 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 common way to create Python decorator?" Next, please follow the editor to study!

Brief introduction of decorator

Decorator is an advanced Python syntax. You can process a function, method, or class. In Python, we have many ways to process functions and classes. Compared with other ways, the decorator has simple syntax and high readability of the code. Therefore, decorators are widely used in Python projects. Modifiers are often used in scenarios with faceted requirements, such as insertion log, performance testing, transaction processing, Web permission verification, Cache and so on.

The advantage of the decorator is that it can extract a large number of functions that have nothing to do with the function itself and continue to reuse. That is, the function can be "modified" into a completely different behavior, which can effectively decompose the business logic orthogonal. In a nutshell, the role of the decorator is to add additional functionality to existing objects. For example, logging requires some functions to be recorded. Stupid way, each function to add code, if the code changes, it will be sad. Decorator way to define a dedicated logging decorator to decorate the required functions.

Def wrapper_out (func): print ('--wrapper_out start--') def inner (* args, * * kwargs): print ("--inner start--") ret = func (* args) * * kwargs) print ("--inner end--") return ret print ('--wrapper_out end--') return inner@wrapper_outdef test (): print ("--test--") return 1 * 2if _ name__ = ='_ main__': print (">") print (test ()) execution result

-- wrapper_out start--

-- wrapper_out end--

>

-- inner start--

-- test--

-- inner end--

two

Source code example def wrapper_out (mode=None) with parameter decorator: print ('--wrapper_out start--') def inner_1 (func): print ("--inner_1 start -") def inner_2 (* args, * * kwargs): print ("--inner_2 start--") print (f "mode: {mode}") ret = func (* args * * kwargs) print ("--inner_2 end--") return ret print ("--inner_2 end -") return inner_2 print ('--wrapper_out end--') return inner_1@wrapper_out (mode=2) def test (): print ("--test--") return 1 * 2if _ name__ = ='_ main__': Print (">") print (test ()) source code result

-- wrapper_out start--

-- wrapper_out end--

-- inner_1 start--

-- inner_2 end--

>

-- inner_2 start--

Mode: 2

-- test--

-- inner_2 end--

two

Source code parsing

The decorator function with parameters, which requires one more layer of nesting, the parameters of the outer decorator

When preloading, it is already loaded according to the writing order of the function.

The execution order calls the outermost decorator function parameters in the corresponding most memory function.

The parameter of the decorated function is passed in as the most inner_1 parameter, and the parameter of the decorated function is passed as the parameter of inner_2.

The execution position of the decorated function is in inner_2, with the assistance of parameter variables of inner_1 and inner_2.

At the same time, you also need to use the parameter variables of the decorator function wrapper_out to do additional operations.

Def wrapper_out1 (func): print ('--wrapper_out_1 start--') def inner1 (* args, * * kwargs): print ("--inner_1 start--") ret = func (* args) * * kwargs) print ("--inner_1 end--") return ret print ('--wrapper_out1 end--') return inner1def wrapper_out2 (func): print ('--wrapper_out_2 start--') def inner2 (* args * * kwargs): print ("--inner_2 start--") print ("--inner_2 end--") print ('--wrapper_out_2 end--') return inner2@wrapper_out2@wrapper_out1def test (): print ("--test--") return 1 * 2if _ name__ = ='_ main__': print (">") print (test ()) execution result

-- wrapper_out_1 start--

-- wrapper_out1 end--

-- wrapper_out_2 start--

-- wrapper_out_2 end--

>

-- inner_2 start--

-- inner_1 start--

-- test--

-- inner_1 end--

-- inner_2 end--

two

Analysis

The preloading order of the decorator is from top to bottom, and the decorator function is written to memory first.

The execution order of the decorator is to start with the decorator closest to the function body (from the inside to the outside).

Class decorator source code example class WrapperOut (object): def _ _ init__ (self, func): print ('start init ~') print ('func name is% s'% func.__name__) self.__func = func print ('end init ~') def _ call__ (self, * args) * * kwargs): print ('start test') self.__func () print (' end test') @ WrapperOutdef test (): print ('this is test func') if _ _ name__ =' _ _ main__': print (">") test () execution result

Start init ~ `

Func name is test

End init ~ `

>

Start test

This is test func

End test

Analysis

The class decorator uses the class initialization init destructor to handle the input of the decorated function.

And using the call method to satisfy the execution trigger of the decorated function

At this point, on the "Python decorator commonly used to create what is the end of the study, 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!

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