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

How to use the Python decorator Decorator

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge of "how to use Python decorator Decorator". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Overlay using Python decorator

Recently, a student asked that there is a @ xxxx syntax similar to Java in Python. What does this mean? Now I will answer that question.

The @ xxxx syntax in Java is Annotation, while the @ xxxx syntax in Python is decorator, which, although similar in syntax, serves a completely different purpose. Java's annotations are equivalent to the metadata of syntax elements (methods, classes, interfaces, and so on). Python's decorator is a wrapper for Python functions (methods). Now let's give an example.

@ makebold @ makeitalic def say (): return "Hello" print (say ())

This code uses two decorators for the function say: @ makebold and @ makeitalic, and is in an overlay state. The @ makeitalic will first act on the say function, and then @ makebold will act on the result of the @ makeitalic decorator, which uses the And. Wraps the string returned by the say function, so the execution result of this code is as follows:

Hello

However, executing this code directly is bound to make an error, because the two decorators have not yet been defined, so let's take a look at how to define them.

two。 Define Python decorator

The decorator itself is an ordinary Python function, but the argument of the function needs to be the function type (usually passed in the decorated function), which is defined as follows:

Hello

Now let's define the two decorators given earlier:

From functools import wraps def makebold (fn): @ wraps (fn) def makebold_wrapped (* args, * * kwargs): return "+ fn (* args, * * kwargs) +" return makebold_wrapped def makeitalic (fn): @ wraps (fn) def makeitalic_wrapped (* args, * * kwargs): return "" + fn (* args, * * kwargs) + "return makeitalic_wrapped

Obviously, makebold and makeitalic are two ordinary Python functions, and two other functions are defined inside the function, and these two functions are returned as return values. This uses the wraps function, which can not be added, but there will be some side effects.

Because when you decorate a function with @ makebold and @ makeitalic, the decorated function is passed to the makebold function and the makeitalic function, that is, the fn parameter is the decorated function. When the decorated function is called externally, the functions returned by the modifier, namely makebold_wrapped and makeitalic_wrapped, are actually called. This will lead to changes in the properties of the decorated function, such as function name, function document, and so on. Now you can remove @ wraps and execute the following code:

@ makeitalic @ makebold def say (): return "Hello" print (say.__name__) # output function name

The following will be output:

Makebold_wrapped

Since the @ makebold decorator is finally used, the output is the name of the makebold_wrapped function returned by the makebold function. If you add @ wraps, you will output say.

Note that you need to call the wraps function through the decorator, which is tantamount to wrapping another layer of decorator (wraps) around @ makebold.

3. Understanding Python function

Now that we know how to customize the Python decorator, how should we understand the decorator? What exactly is the principle? To understand the Python decorator, you should first know that the Python function is an object. Take a look at the following example:

Def shout (word= "yes"): return word.capitalize () # output: Yes print (shout ()) # assigns the shout function to another variable without using parentheses, # so instead of calling the function, it assigns the function to another variable, that is, to give the function an alias scream = shout # you can call the shout function # output with scream: Yes print (scream ()) # currently, the same function There are two references: scream and shout. You can use del to delete a reference del shout try: # after the reference is deleted, the function print (shout ()) except NameError as e: print (e) # can still be called through another reference # output: Yes print (scream ())

This code demonstrates using a function as an object. If you add a pair of parentheses, you are calling the function. If you do not add a pair of parentheses, the function is an object, which can be assigned to another variable or passed into the function as a function parameter value.

Because the Python function itself is an object, it can be defined anywhere, including the function content. This is the Python built-in function. The code is as follows:

Def talk (): # embedded function def whisper (word= "YES"): return word.lower () + "..." # call embedded function print (whisper ()) # calling talk,whisper function is called inside talk # output: yes... Talk () try: # but the whisper function is not visible outside the talk function, so the call throws an exception print (whisper ()) except NameError as e: print (e)

To sum up now, the features of the Python function are as follows:

(1) you can assign the function itself to a variable, or pass in the function as a parameter value (method)

(2) can be defined inside a function (method)

With these two features, it means that a function can be returned by another function, as shown in the following code:

Def getTalk (kind= "shout"): # define the first embedded function def shout (word= "yes"): return word.capitalize () + "!" # define the second embedded function def whisper (word= "yes"): return word.lower () + "..." # return a specific function if kind= = "shout" based on the parameter value: # A pair of parentheses are not used here So instead of calling the function, it returns the function itself return shout else: return whisper # talk is the function itself, and is not called talk = getTalk () # output function itself # output: print (talk) # call talk function (actually shout function) print (talk ()) # outputs: Yes! # call whisper function print (getTalk ("whisper") ())

In this code, the getTalk function returns different embedded functions based on the value of the kind parameter, so the return value of the getTalk function is the function itself, or function object, and if you want to call the function, you need to use a pair of parentheses, such as getTalk () ().

Based on this feature, we can do more, for example, to automatically do other work before calling a function, see the following code:

Def doSomethingBefore (func): print ("I do something before then I call the function you gave me") print (func ()) doSomethingBefore (talk)

In fact, this code wraps talk with the doSomethingBefore function, so that you can call the talk function through the doSomethingBefore function and output a line of text before calling the talk function.

4. The principle of Python decorator

After understanding the Python function, it is much easier to understand the Python decorator. Cut the crap and take a look at the following code:

# decorator function, argument is another function (decorated function) def my_shiny_new_decorator (a_function_to_decorate): # decorator embedded function Used to wrap the decorated function def the_wrapper_around_the_original_function (): # output a line of text print ("Before the function runs") before calling the decorated function # call the decorated function a_function_to_decorate () # output a line of text print (" After the function runs ") # returns the wrapper function return the_wrapper_around_the_original_function # this function will be decorated by the my_shiny_new_decorator function def a_stand_alone_function (): print (" I am a stand alone function " Don't you dare modify me ") # call function a_stand_alone_function () # decorate the a_stand_alone_function function a_stand_alone_function_decorated = my_shiny_new_decorator (a_stand_alone_function) a_stand_alone_function_decorated ()

If you execute this code, you will output the following:

I am a stand alone function, don't you dare modify me Before the function runs I am a stand alone function, don't you dare modify me After the function runs

In this code, the a_stand_alone_function function is decorated with the my_shiny_new_decorator function, and a line of text is output before and after calling the a_stand_alone_function function. In fact, this is what the Python decorator is for: wrapper functions. It's just that the decorator syntax is not used here, but the decorator function is called directly in the simplest way to modify the a_stand_alone_function function.

If you decorate the a_stand_alone_function function with a decorator, you can use the following code.

My_shiny_new_decorator def a_stand_alone_function (): print ("I am a stand alone function, don't you dare modify me")

When the a_stand_alone_function function is called, the a_stand_alone_function function is automatically wrapped with the my_shiny_new_decorator function, that is, @ my_shiny_new_decorator is the abbreviated form of my_shiny_new_decorator (a_stand_alone_function).

This is the end of "how to use the Python decorator Decorator". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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