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 talk about decorator in Python

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is to share with you about how to talk about decorators in Python, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

What is a decorator?

A decorator is a code tool used to encapsulate a function or class, explicitly acting the wrapper on the function or class to achieve the purpose of dynamically adding functionality when the program is running. Handle common preconditions before the function is run (common web login authorization verification), or do the aftermath after the function is executed (such as exception handling, logging log, etc.).

How to use the decorator

The decorator is essentially a high-order function that can accept calls or return calls. This function takes the decorated function as an argument (you can also add other values as arguments). Perform the logic processing of the decorator in the decorator, execute the decorated function, and return a decorated function, which sounds a little Talk is cheap,show me the code.

The following uses the function now and function add as examples

Import datetime

Def now ():

Print 'now is', datetime.datetime.today ()

Def add (x, y):

Ret = x + y

Print'{x} + {y} = {retval} '.format

2.1 decorator syntax

There are two ways to display the method of calling the decorator.

Method 1: func = deco (func)

Method 2: after Python 2.5, a special syntax @-syntax sugar is introduced for the decorator, using the @ symbol before the decorator name and before the decorated function definition.

@ deco

Def now ():

Print 'now is', datetime.datetime.today ()

# call now

Now ()

The editor will introduce the decorator from the point of view of parameters, the function has two cases with and without parameters, and the decorator also has two cases with and without parameters. The decorator will also have different locks for dealing with the situation with and without parameters.

2.2 cases without parameters

We need to add call records before and after calling the function now.

Def deco (func):

Print 'begin call% s ():'% (func.__name__)

Func ()

Print 'end call% s ():'% (func.__name__)

The argument to the return func # decorator is the decorated function object that returns the object of the original function.

YangyiDBA:test yangyi$ python 1.py

Begin call now ():

Now is 2017-05-01 1440 57.309836

End call now ():

Now is 2017-05-01 1440 purl 57.309868

However, from the above example, we can see that the now time is output twice, which obviously does not meet our requirements, because the decorator must return the called function, and the second time occurs when return func. We will solve this problem later.

2.3 in the case of parameters, because the number of parameters of the function is uncertain, we need to use (* args, * * kwargs) to automatically adapt to variable parameters and named parameters.

#! / usr/bin/env python

# coding:utf-8

Import datetime

Import functools

Def deco (func):

@ functools.wraps (func) #

Def wrapper (* args, * * kw):

Print 'begin call% s ():'% (func.__name__)

Result=func (* args, * * kw) # if the function does not return a value, you can directly use func (* args, * * kw)

Print 'end call% s ():'% (func.__name__)

Return result # result here is for func to have a return value

Return wrapper

@ deco

Def add (x, y):

Ret = x + y

Print'{x} + {y} = {retval} '.format

@ deco

Def now ():

Print 'now is', datetime.datetime.today ()

Add (2 and 5)

Now ()

The above decorator does the following

The 1 function func is passed to deco () as an argument.

2 functool.wraps copies the properties of func to warper.

(3) perform some actions before and after executing the function func.

4 return the result.

5 returns the wrapper function object.

The role of functool.wraps is highlighted here, because the decorator causes the interpreter to think that the function itself has changed, which may cause problems in some cases. Python solved this problem through functool.wraps:

When writing a decorator, adding @ functools.wraps (func) before implementation ensures that the decorator will not affect the decorated function.

In particular, there are other ways to write when you want to use the decorator, such as directly returning the decorated function.

Def deco (func):

@ functools.wraps (func) #

Def wrapper (* args, * * kw):

Print 'begin call% s ():'% (func.__name__)

Return func (* args, * * kw)

Return wrapper

Output

YangyiDBA:test yangyi$ python 1.py

Begin call add ():

2 + 5 = 7

End call add ():

Begin call now ():

Now is 2017-05-01 15 purl 20 purl 51.597859

End call now ():

2.4 Decoration with parameters

If the decorator itself passes in parameters, you need to write a higher-order function that returns decorator, which is more complicated to write. For example, to customize the text of log:

#! / usr/bin/env python

# coding:utf-8

Import datetime

Import functools

Def deco (text):

Def _ deco (func):

Def wrapper (* args, * * kw):

Print's, begin call% s ():'% (text,func.__name__)

Result=func (* args, * * kw) # if the function does not return a value, you can directly use func (* args, * * kw)

Print's, end call% s ():'% (text,func.__name__)

Return result # result here is for func to have a return value

Return wrapper

Return _ deco

@ deco ("yangyi")

Def add (x, y):

Ret = x + y

Print'{x} + {y} = {retval} '.format

@ deco ("youzan")

Def now ():

Print 'now is', datetime.datetime.today ()

Add (2 and 5)

Now ()

Test results:

YangyiDBA:test yangyi$ python 2.py

Yangyi, begin call add ():

2 + 5 = 7

Yangyi, end call add ():

Youzan, begin call now ():

Now is 2017-05-01 18 purl 47 purl 54.728296

Youzan, end call now ():

2.5 Python built-in decorator

There are three built-in decorators in Python, all related to class: staticmethod, classmethod, and property.

Staticmethod is a class static method, which differs from a member method in that it has no self parameter and can be called without class instantiation.

Classmethod differs from member methods in that the first parameter received is not self (the pointer to the class instance), but cls (the concrete type of the current class).

Property is an attribute that represents information that can be accessed directly through an instance of a class.

2.6 cross-file calls, because the decorator is essentially a function. In the engineering implementation, we can create a common decorator as the basic decorator for other functions to call.

Python everything is an object, and so are functions, and you can assign values to other variables, which is much easier to understand and then to understand the decorator.

The above is how to talk about decorators in Python. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.

Share To

Internet Technology

Wechat

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

12
Report