Python装饰器的从入门到高阶用法详解!

首先要恭喜你,点进了这一篇十足干货。

不怕感动自己,这篇文章,小编足足整理了三天之久。绝对值得收藏,以备后用。

今天小明要讲的是,Python中的装饰器内容。

我会从装饰器的入门用法逐步讲到其高阶用法

进群进群:700341555可以获取Python各类入门学习资料!

这是我的微信公众号【Python编程之家】各位大佬用空可以关注下,每天更新Python学习方法,感谢!

111111111111.png

image

目录如下

  • 装饰器语法糖
  • 入门用法:日志打印器
  • 入门用法:时间计时器
  • 进阶用法:带参数的函数装饰器
  • 高阶用法:不带参数的类装饰器
  • 高阶用法:带参数的类装饰器
  • 内置装饰器:property
  • 其他装饰器:装饰器实战

. 装饰器语法糖

如果你接触 Python 有一段时间了的话,想必你对 @ 符号一定不陌生了,没错 @ 符号就是装饰器的语法糖。

它放在函数开始定义的地方,它就像一顶帽子一样戴在函数的头上。和这个函数绑定在一起。在我们调用这个函数的时候,第一件事并不是执行这个函数,而是将这个函数做为参数传入它头顶上这顶帽子,这顶帽子我们称之为装饰函数 或 装饰器。

你要问我装饰器可以实现什么功能?这个真的是无解,小明只能说你的脑洞有多大,装饰器就有多强大。

装饰器的使用方法很固定:

  • 先定义一个装饰函数(帽子)
  • 再定义你的业务函数(人)
  • 最后把这顶帽子带在这个人头上

装饰器的简单的用法有很多,这里举两个常见的。

  • 日志打印器
  • 时间计时器

. 入门用法:日志打印器

首先是日志打印器

实现的功能:

在函数执行前,先打印一行日志告知一下主人,我要执行函数了。在函数执行完,也不能拍拍屁股就走人了,咱可是有礼貌的代码,再打印一行日志告知下主人,我执行完啦。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

# 这是装饰函数
def logger(func):
 def wrapper(*args, **kw):
 print('我准备开始计算:{} 函数了:'.format(func.__name__))
 # 真正执行的是这行。
 func(*args, **kw)
 print('啊哈,我计算完啦。给自己加个鸡腿!!')
 return wrapper

</pre>

假如,我的业务函数是,计算两个数之和。写好后,直接给它带上帽子。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

@logger
def add(x, y):
 print('{} + {} = {}'.format(x, y, x+y))

</pre>

然后我们来计算一下。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

add(200, 50)

</pre>

快来看看输出了什么,神奇不?

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

我准备开始计算:add 函数了:
200 + 50 = 250
啊哈,我计算完啦。给自己加个鸡腿!

</pre>

. 入门用法:时间计时器

再来看看 时间计时器

实现功能:

顾名思义,就是计算一个函数的执行时长。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

# 这是装饰函数
def timer(func):
 def wrapper(*args, **kw):
 t1=time.time()
 # 这是函数真正执行的地方
 func(*args, **kw)
 t2=time.time()
 # 计算下时长
 cost_time = t2-t1 
 print("花费时间:{}秒".format(cost_time))
 return wrapper

</pre>

假如,我们的函数是要睡眠 2秒(冏~,小明实在不知道要举什么例子了)。这样也能更好的看出这个计算时长到底靠不靠谱。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

import time
@timer
def want_sleep(sleep_time):
 time.sleep(sleep_time)
want_sleep( 2)

</pre>

来看看,输出。真的是2秒耶。真历害!!!

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

花费时间:2.0073800086975098秒

</pre>

. 进阶用法:带参数的函数装饰器

通过上面简单的入门,你大概已经感受到了装饰的神奇魅力了。

不过,装饰器的用法远不止如此。我们今天就要把这个知识点讲透。

上面的例子,装饰器是不能接收参数的。其用法,只能适用于一些简单的场景。不传参的装饰器,只能对被装饰函数,执行固定逻辑。

如果你有经验,你一定经常在项目中,看到有的装饰器是带有参数的。

装饰器本身是一个函数,既然做为一个函数都不能携带函数,那这个函数的功能就很受限。只能执行固定的逻辑。这无疑是非常不合理的。而如果我们要用到两个内容大体一致,只是某些地方不同的逻辑。不传参的话,我们就要写两个装饰器。小明觉得这不能忍。

那么装饰器如何实现传参呢,会比较复杂,需要两层嵌套。

同样,我们也来举个例子。

我们要在这两个函数的执行的时候,分别根据其国籍,来说出一段打招呼的话。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

def american():
 print("我来自中国。")
def chinese():
 print("I am from America.")

</pre>

在给他们俩戴上装饰器的时候,就要跟装饰器说,这个人是哪国人,然后装饰器就会做出判断,打出对应的招呼。

戴上帽子后,是这样的。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

@say_hello("china")
def american():
 print("我来自中国。")
@say_hello("america")
def chinese():
 print("I am from America.")

</pre>

万事俱备,只差帽子了。来定义一下,这里需要两层嵌套。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

def say_hello(contry):
 def wrapper(func):
 def deco(*args, **kwargs):
 if contry == "china":
 print("你好!")
 elif contry == "america":
 print('hello.')
 else:
 return
 # 真正执行函数的地方
 func(*args, **kwargs)
 return deco
 return wrapper

</pre>

执行一下

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

american()
print("------------")
chinese()

</pre>

看看输出结果。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

你好!
我来自中国。
------------
hello.
I am from America

</pre>

emmmm,这很NB。。。

. 高阶用法:不带参数的类装饰器

以上都是基于函数实现的装饰器,在阅读别人代码时,还可以时常发现还有基于类实现的装饰器。

基于类装饰器的实现,必须实现 call 和 init两个内置函数。

init :接收被装饰函数

call :实现装饰逻辑。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

class logger(object):
 def __init__(self, func):
 self.func = func
 def __call__(self, *args, **kwargs):
 print("[INFO]: the function {func}() is running..."\
 .format(func=self.func.__name__))
 return self.func(*args, **kwargs)
@logger
def say(something):
 print("say {}!".format(something))
say("hello")

</pre>

执行一下,看看输出

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

[INFO]: the function say() is running...
say hello!

</pre>

. 高阶用法:带参数的类装饰器

上面不带参数的例子,你发现没有,只能打印INFO级别的日志,正常情况下,我们还需要打印DEBUG WARNING等级别的日志。 这就需要给类装饰器传入参数,给这个函数指定级别了。

带参数和不带参数的类装饰器有很大的不同。

init :不再接收被装饰函数,而是接收传入参数。

call :接收被装饰函数,实现装饰逻辑。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

class logger(object):
 def __init__(self, level='INFO'):
 self.level = level
 def __call__(self, func): # 接受函数
 def wrapper(*args, **kwargs):
 print("[{level}]: the function {func}() is running..."\
 .format(level=self.level, func=func.__name__))
 func(*args, **kwargs)
 return wrapper #返回函数
@logger(level='WARNING')
def say(something):
 print("say {}!".format(something))
say("hello")

</pre>

我们指定WARNING级别,运行一下,来看看输出。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

[WARNING]: the function say() is running...
say hello!

</pre>

. 内置装饰器:property

以上,我们介绍的都是自定义的装饰器。

其实Python语言本身也有一些装饰器。比如property这个内建装饰器,我们再熟悉不过了。

它通常存在于类中,可以将一个函数定义成一个属性,属性的值就是该函数return的内容。

通常我们给实例绑定属性是这样的

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

class Student(object):
 def __init__(self, name, age=None):
 self.name = name
 self.age = age
# 实例化
XiaoMing = Student("小明")
# 添加属性
XiaoMing.age=25
# 查询属性
XiaoMing.age
# 删除属性
del XiaoMing.age

</pre>

但是稍有经验的开发人员,一下就可以看出,这样直接把属性暴露出去,虽然写起来很简单,但是并不能对属性的值做合法性限制。为了实现这个功能,我们可以这样写。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

class Student(object):
 def __init__(self, name):
 self.name = name
 self.name = None
 def set_age(self, age):
 if not isinstance(age, int):
 raise ValueError('输入不合法:年龄必须为数值!')
 if not 0 < age < 100:
 raise ValueError('输入不合法:年龄范围必须0-100')
 self._age=age
 def get_age(self):
 return self._age
 def del_age(self):
 self._age = None
XiaoMing = Student("小明")
# 添加属性
XiaoMing.set_age(25)
# 查询属性
XiaoMing.get_age()
# 删除属性
XiaoMing.del_age()

</pre>

上面的代码设计虽然可以变量的定义,但是可以发现不管是获取还是赋值(通过函数)都和我们平时见到的不一样。

按照我们思维习惯应该是这样的。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

# 赋值
XiaoMing.age = 25
# 获取
XiaoMing.age

</pre>

那么这样的方式我们如何实现呢。请看下面的代码。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

class Student(object):
 def __init__(self, name):
 self.name = name
 self.name = None
 @property
 def age(self):
 return self._age
 @age.setter
 def age(self, value):
 if not isinstance(value, int):
 raise ValueError('输入不合法:年龄必须为数值!')
 if not 0 < value < 100:
 raise ValueError('输入不合法:年龄范围必须0-100')
 self._age=value
 @age.deleter
 def age(self):
 del self._age
XiaoMing = Student("小明")
# 设置属性
XiaoMing.age = 25
# 查询属性
XiaoMing.age
# 删除属性
del XiaoMing.age

</pre>

用@property装饰过的函数,会将一个函数定义成一个属性,属性的值就是该函数return的内容。同时,会将这个函数变成另外一个装饰器。就像后面我们使用的@age.setter和@age.deleter。

@age.setter 使得我们可以使用XiaoMing.age = 25这样的方式直接赋值。

@age.deleter 使得我们可以使用del XiaoMing.age这样的方式来删除属性。

. 其他装饰器:装饰器实战

读完并理解了上面的内容,你可以说是Python高手了。别怀疑,自信点,因为很多人都不知道装饰器有这么多用法呢。

在小明看来,使用装饰器,可以达到如下目的:

  • 使代码可读性更高,逼格更高;
  • 代码结构更加清晰,代码冗余度更低;

刚好小明在最近也有一个场景,可以用装饰器很好的实现,暂且放上来看看。

这是一个实现控制函数运行超时的装饰器。如果超时,则会抛出超时异常。

有兴趣的可以看看。

<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

import signal
class TimeoutException(Exception):
 def __init__(self, error='Timeout waiting for response from Cloud'):
 Exception.__init__(self, error)
def timeout_limit(timeout_time):
 def wraps(func):
 def handler(signum, frame):
 raise TimeoutException()
 def deco(*args, **kwargs):
 signal.signal(signal.SIGALRM, handler)
 signal.alarm(timeout_time)
 func(*args, **kwargs)
 signal.alarm(0)
 return deco
 return wraps

</pre>

猜你喜欢

转载自blog.csdn.net/weixin_44138053/article/details/86148796