Summarize the knowledge points of decorators in Python

WBOY
Release: 2022-06-17 13:50:40
forward
2293 people have browsed it

This article brings you relevant knowledge aboutpython, which mainly introduces related issues about decorators, including closures, decorators, using multiple decorators, and parameters. Decorators and other contents, let’s take a look at them below. I hope it will be helpful to everyone.

Summarize the knowledge points of decorators in Python

Recommended learning:python video tutorial

1. Closure

To understand what isDecorator(decorator), we first need to know the concept ofclosure(closure).

Closure, also known as closure function or closed function, generally speaking, when a function is returned as an object and also entrains external variables, a closure is formed.

Taking printing Hello World as an example, let's first take a look at what the structure of the nested function should look like:

def print_msg(msg): def printer(): print(msg) printer()print_msg('Hello World')# Hello World
Copy after login

Executionprint_msg('Hello World')It is equivalent to executingprinter(), that is, executingprint(msg), soHello Worldwill be output.

Let’s take a look at what kind of structure it would be if it were a closure:

def print_msg(msg): def printer(): print(msg) return printer my_msg = print_msg('Hello World')my_msg()# Hello World
Copy after login

Theprinterfunction in this example is a closure.

Executionprint_msg('Hello World')actually returns a function like the following, which entrains external variables'Hello World':

def printer(): print('Hello World')
Copy after login

So callingmy_msgis equivalent to executingprinter().


So how to determine whether a function is a closure function? The__closure__attribute of the closure function defines a tuple for storing all cell objects. Each cell object stores all external variables in the closure. The__closure__attribute of a normal function isNone.

def outer(content): def inner(): print(content) return innerprint(outer.__closure__) # Noneinner = outer('Hello World')print(inner.__closure__) # (,)
Copy after login

It can be seen that theouterfunction is not a closure, and theinnerfunction is a closure.

We can also view the external variables carried by the closure:

print(inner.__closure__[0].cell_contents)# Hello World
Copy after login

Having said so much, what is the use of closures? The meaning of the existence of a closure is that it carries external variables (private goods). If it does not carry private goods, then it is no different from an ordinary function.

The advantages of closures are as follows:

  • Local variables cannot be shared and saved for a long time, while global variables may cause variable pollution. Closures can save variables for a long time without causing pollution. Global contamination.
  • Closure allows the value of local variables within the function to always remain in memory and will not be automatically cleared after the external function is called.

2. Decorator

Let’s first consider such a scenario. Assume that a previously written function has implemented 4 functions. For simplicity, we useprintstatement to represent each specific function:

def module(): print('功能1') print('功能2') print('功能3') print('功能4')
Copy after login

Now, for some reason, you need to add afunction 5to themodulefunction, you It can be modified like this:

def module(): print('功能1') print('功能2') print('功能3') print('功能4') print('功能5')
Copy after login

But in real business, it is often dangerous to make such modifications directly (it will become difficult to maintain). SoHow to add a new function to it without modifying the original function?

You may have thought of using the previous closure knowledge:

def func_5(original_module): def wrapper(): original_module() print('功能5') return wrapper
Copy after login

func_5means that the function is mainly used to implementfunction 5, we will next passmodulein to observe the effect:

new_module = func_5(module)new_module()# 功能1# 功能2# 功能3# 功能4# 功能5
Copy after login

It can be seen that our new module:new_modulehas implementedfunction 5.

In the above example, functionfunc_5is a decorator, which decorates the original module (adds a new function to it).

Of course, Python has a more concise way of writing (called syntactic sugar), we can use the @ symbol with the name of the decorator function and place it in the definition of the function to be decorated Above:

def func_5(original_module): def wrapper(): original_module() print('功能5') return wrapper@func_5def module(): print('功能1') print('功能2') print('功能3') print('功能4')module()# 功能1# 功能2# 功能3# 功能4# 功能5
Copy after login

Based on this, we can complete the timing task (calculate the running time of the original function) without modifying the original function, as follows:

def timer(func): def wrapper(): import time tic = time.time() func() toc = time.time() print('程序用时: {}s'.format(toc - tic)) return wrapper@timerdef make_list(): return [i * i for i in range(10**7)]my_list = make_list()# 程序用时: 0.8369960784912109s
Copy after login

In fact,my_listis not a list. Direct printing will displayNone. This is because ourwrapperfunction does not set a return value. If you need to get the return value ofmake_list, you can modify thewrapperfunction like this:

def wrapper(): import time tic = time.time() a = func() toc = time.time() print('程序用时: {}s'.format(toc - tic)) return a
Copy after login

3. Use multiple decorators

If we want tomoduleNewly addedfunction 5andfunction 6(in numerical order), what should I do?

Fortunately, Python allows the use of multiple decorators at the same time:

def func_5(original_module): def wrapper(): original_module() print('功能5') return wrapperdef func_6(original_module): def wrapper(): original_module() print('功能6') return wrapper@func_6@func_5def module(): print('功能1') print('功能2') print('功能3') print('功能4')module()# 功能1# 功能2# 功能3# 功能4# 功能5# 功能6
Copy after login

The above process is actually equivalent to:

def module(): print('功能1') print('功能2') print('功能3') print('功能4')new_module = func_6(func_5(module))new_module()
Copy after login

In addition, it should be noted that when using multiple decorators When decorating a decorator,the decorator closest to the function definition will decorate the function first. If we change the decoration order, the output result will also change:

@func_5@func_6def module(): print('功能1') print('功能2') print('功能3') print('功能4')module()# 功能1# 功能2# 功能3# 功能4# 功能6# 功能5
Copy after login

4. Decorated function With parameters

If the decorated function has parameters, how to construct the decorator?

Consider such a function:

def pide(a, b): return a / b
Copy after login

b=0时会出现ZeropisionError。如何在避免修改该函数的基础上给出一个更加人性化的提醒呢?

因为我们的pide函数接收两个参数,所以我们的wrapper函数也应当接收两个参数:

def smart_pide(func): def wrapper(a, b): if b == 0: return '被除数不能为0!' else: return func(a, b) return wrapper
Copy after login

使用该装饰器进行装饰:

@smart_pidedef pide(a, b): return a / bprint(pide(3, 0))# 被除数不能为0!print(pide(3, 1))# 3.0
Copy after login

如果不知道要被装饰的函数有多少个参数,我们可以使用下面更为通用的模板:

def decorator(func): def wrapper(*args, **kwargs): # ... res = func(*args, **kwargs) # ... return res # 也可以不return return wrapper
Copy after login

五、带参数的装饰器

我们之前提到的装饰器都没有带参数,即语法糖@decorator中没有参数,那么该如何写一个带参数的装饰器呢?

前面实现的装饰器都是两层嵌套函数,而带参数的装饰器是一个三层嵌套函数。

考虑这样一个场景。假如我们在为module添加新功能时,希望能够加上实现该功能的开发人员的花名,则可以这样构造装饰器(以功能5为例):

def func_5_with_name(name=None): def func_5(original_module): def wrapper(): original_module() print('功能5由{}实现'.format(name)) return wrapper return func_5
Copy after login

效果如下:

@func_5_with_name(name='若水')def module(): print('功能1') print('功能2') print('功能3') print('功能4')module()# 功能1# 功能2# 功能3# 功能4# 功能5由若水实现
Copy after login

对于这种三层嵌套函数,我们可以这样理解:当为func_5_with_name指定了参数后,func_5_with_name(name='若水')实际上返回了一个decorator,于是@func_5_with_name(name='若水')就相当于@decorator

六、使用类作为装饰器

将类作为装饰器,我们需要实现__init__方法和__call__方法。

以计时器为例,具体实现如下:

class Timer: def __init__(self, func): self.func = func def __call__(self): import time tic = time.time() self.func() toc = time.time() print('用时: {}s'.format(toc - tic))@Timerdef make_list(): return [i**2 for i in range(10**7)]make_list()# 用时: 2.928966999053955s
Copy after login

如果想要自定义生成列表的长度并获得列表(即被装饰的函数带有参数情形),我们就需要在__call__方法中传入相应的参数,具体如下:

class Timer: def __init__(self, func): self.func = func def __call__(self, num): import time tic = time.time() res = self.func(num) toc = time.time() print('用时: {}s'.format(toc - tic)) return res@Timerdef make_list(num): return [i**2 for i in range(num)]my_list = make_list(10**7)# 用时: 2.8219943046569824sprint(len(my_list))# 10000000
Copy after login

如果要构建带参数的类装饰器,则不能把func传入__init__中,而是传入到__call__中,同时__init__用来初始化类装饰器的参数。

接下来我们使用类装饰器来复现第五章节中的效果:

class Func_5: def __init__(self, name=None): self.name = name def __call__(self, func): def wrapper(): func() print('功能5由{}实现'.format(self.name)) return wrapper@Func_5('若水')def module(): print('功能1') print('功能2') print('功能3') print('功能4')module()# 功能1# 功能2# 功能3# 功能4# 功能5由若水实现
Copy after login

七、内置装饰器

Python中有许多内置装饰器,这里仅介绍最常见的三种:@classmethod@staticmethod@property

7.1 @classmethod

@classmethod用于装饰类中的函数,使用它装饰的函数不需要进行实例化也可调用。需要注意的是,被装饰的函数不需要self参数,但第一个参数需要是表示自身类的cls参数,它可以来调用类的属性,类的方法,实例化对象等。

cls代表类本身,self代表实例本身。

具体请看下例:

class A: num = 100 def func1(self): print('功能1') @classmethod def func2(cls): print('功能2') print(cls.num) cls().func1()A.func2()# 功能2# 100# 功能1
Copy after login

7.2 @staticmethod

@staticmethod同样用来修饰类中的方法,使用它装饰的函数的参数没有任何限制(即无需传入self参数),并且可以不用实例化调用该方法。当然,实例化后调用该方法也是允许的。

具体如下:

class A: @staticmethod def add(a, b): return a + bprint(A.add(2, 3))# 5print(A().add(2, 3))# 5
Copy after login

7.3 @property

使用@property装饰器,我们可以直接通过方法名来访问类方法,不需要在方法名后添加一对()小括号。

class A: @property def printer(self): print('Hello World')a = A()a.printer# Hello World
Copy after login

除此之外,@property还可以用来防止类的属性被修改。考虑如下场景

class A: def __init__(self): self.name = 'ABC'a = A()print(a.name)# ABCa.name = 1print(a.name)# 1
Copy after login

可以看出类中的属性name可以被随意修改。如果要防止修改,则可以这样做

class A: def __init__(self): self.name_ = 'ABC' @property def name(self): return self.name_ a = A()print(a.name)# ABCa.name = 1print(a.name)# AttributeError: can't set attribute
Copy after login

推荐学习:python视频教程

The above is the detailed content of Summarize the knowledge points of decorators in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!