python 装饰器的基本使用


Posted in Python onJanuary 13, 2021

知识点

  • 简单的装饰器
  • 带有参数的装饰器
  • 带有自定义参数的装饰器
  • 类装饰器
  • 装饰器嵌套
  • @functools.wrap装饰器使用

基础使用

简单的装饰器

def my_decorator(func):
  def wrapper():
    print('wrapper of decorator')
    func()
  return wrapper()


def test():
  print('test done.')

test = my_decorator(test)
test

输出:
wrapper of decorator
test done.

这段代码中,变量test指向了内部函数wrapper(), 而内部函数wrapper()中又会调用原函数test(),因此最后调用test()时,就会打印'wrapper of decorator' 然后输出 'test done.'

这里的函数my_decorator()就是一个装饰器,它把真正需要执行的函数test()包裹在其中,并且改变了它的行为,但是原函数test()不变。

上述代码在Python中更简单、更优雅的表示:

def my_decorator(func):
  def wrapper():
    print('wrapper of decorator')
    func()
  return wrapper()

@my_decorator
def test():
  print('test done.')

test

这里的@, 我们称为语法糖,@my_decorator就相当于前面的test=my_decorator(test)语句

如果程序中又其他函数需要类似装饰,只需要加上@decorator就可以,提高函数的重复利用和程序可读性

带有参数的装饰器

def args_decorator(func):
  def wrapper(*args, **kwargs):
    print('wrapper of decorator')
    func(*args, **kwargs)
  return wrapper

@args_decorator
def identity(name, message):
  print('identity done.')
  print(name, message)

identity('changhao', 'hello')

输出:
wrapper of decorator
identity done.
changhao hello

通常情况下,会把args和*kwargs,作为装饰器内部函数wrapper()的参数。 表示接受任意数量和类型的参数

带有自定义参数的装饰器

定义一个参数,表示装饰器内部函数被执行的次数,可以写成这个形式:

def repeat(num):
  def my_decorator(func):
    def wrapper(*args, **kwargs):
      for i in range(num):
        func(*args, **kwargs)
    return wrapper
  return my_decorator


@repeat(3)
def showname(message):
  print(message)

showname('changhao')

输出:
changhao
changhao
changhao

类装饰器

类也可以作装饰器,类装饰器主要依赖于函数 __call__每当调用一个示例时,函数__call__()就会被执行一次。

class Count:
  def __init__(self, func):
    self.func = func
    self.num_calls = 0

  def __call__(self, *args, **kwargs):
    self.num_calls += 1
    print('num of calls is: {}'.format(self.num_calls))
    return self.func(*args, **kwargs)


@Count
def example():
  print('example done.')

example()
example()

输出:
num of calls is: 1
example done.
num of calls is: 2
example done.

这里定义了类Count,初始化时传入原函数func(),而__call__()函数表示让变量num_calls自增1,然后打印,并且调用原函数。因此我们第一次调用函数example()时,num_calls的值是1,而第一次调用时,值变成了2。

装饰器的嵌套

import functools
def my_decorator1(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    print('execute decorator1')
    func(*args, **kwargs)
  return wrapper


def my_decorator2(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    print('execute decorator2')
    func(*args, **kwargs)
  return wrapper


@my_decorator1
@my_decorator2
def test2(message):
  print(message)


test2('changhao')

输出:
execute decorator1
execute decorator2
changhao

类装饰器

类也可以作装饰器,类装饰器主要依赖于函数 __call__每当调用一个示例时,函数__call__()就会被执行一次。

class Count:
  def __init__(self, func):
    self.func = func
    self.num_calls = 0

  def __call__(self, *args, **kwargs):
    self.num_calls += 1
    print('num of calls is: {}'.format(self.num_calls))
    return self.func(*args, **kwargs)


@Count
def example():
  print('example done.')

example()
example()

输出:
num of calls is: 1
example done.
num of calls is: 2
example done.

这里定义了类Count,初始化时传入原函数func(),而__call__()函数表示让变量num_calls自增1,然后打印,并且调用原函数。因此我们第一次调用函数example()时,num_calls的值是1,而第一次调用时,值变成了2。

装饰器的嵌套

import functools
def my_decorator1(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    print('execute decorator1')
    func(*args, **kwargs)
  return wrapper


def my_decorator2(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    print('execute decorator2')
    func(*args, **kwargs)
  return wrapper


@my_decorator1
@my_decorator2
def test2(message):
  print(message)


test2('changhao')

输出:
execute decorator1
execute decorator2
changhao

@functools.wrap装饰器使用

import functools
def my_decorator(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    print('wrapper of decorator')
    func(*args, **kwargs)
    return wrapper

@my_decorator
def test3(message):
  print(message)

test3.__name__ 

输出
test3

通常使用内置的装饰器@functools.wrap,他会保留原函数的元信息(也就是将原函数的元信息,拷贝到对应的装饰器里)

装饰器用法实例

身份认证

import functools

def authenticate(func):
 @functools.wraps(func)
 def wrapper(*args, **kwargs):
  request = args[0]
  if check_user_logged_in(request):
   return func(*args, **kwargs)
    else:
   raise Exception('Authentication failed')
  return wrapper

@authenticate
def post_comment(request):
 pass

这段代码中,定义了装饰器authenticate;而函数post_comment(),则表示发表用户对某篇文章的评论。每次调用这个函数前,都会检查用户是否处于登录状态,如果是登录状态,则允许这项操作;如果没有登录,则不允许。

日志记录

import time
import functools

def log_execution_time(func):
 @functools.wraps(func)
 def wrapper(*args, **kwargs):
  start = time.perf_counter()
  res = func(*args, **kwargs)
  end = time.perf_counter()
  print('{} took {} ms'.format(func.__name__, (end - start) * 1000))
  return wrapper

@log_execution_time
def calculate_similarity(times):
 pass

这里装饰器log_execution_time记录某个函数的运行时间,并返回其执行结果。如果你想计算任何函数的执行时间,在这个函数上方加上@log_execution_time即可。

总结

所谓装饰器,其实就是通过装饰器函数,来修改原函数的一些功能,使得原函数不需要修改。

以上就是python 装饰器的基本使用的详细内容,更多关于python 装饰器的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python实现计算资源图标crc值的方法
Oct 05 Python
Python使用正则匹配实现抓图代码分享
Apr 02 Python
python使用multiprocessing模块实现带回调函数的异步调用方法
Apr 18 Python
Python使用functools实现注解同步方法
Feb 06 Python
django用户登录和注销的实现方法
Jul 16 Python
python实现linux下抓包并存库功能
Jul 18 Python
使用Python和Prometheus跟踪天气的使用方法
May 06 Python
对PyQt5中树结构的实现方法详解
Jun 17 Python
Pytorch 实现数据集自定义读取
Jan 18 Python
Pycharm及python安装详细步骤及PyCharm配置整理(推荐)
Jul 31 Python
Python实现加密的RAR文件解压的方法(密码已知)
Sep 11 Python
python excel多行合并的方法
Dec 09 Python
python日志通过不同的等级打印不同的颜色(示例代码)
Jan 13 #Python
浅谈Selenium+Webdriver 常用的元素定位方式
Jan 13 #Python
Selenium Webdriver元素定位的八种常用方式(小结)
Jan 13 #Python
基于python+selenium自动健康打卡的实现代码
Jan 13 #Python
Python爬虫scrapy框架Cookie池(微博Cookie池)的使用
Jan 13 #Python
matplotlib交互式数据光标实现(mplcursors)
Jan 13 #Python
Python 生成短8位唯一id实战教程
Jan 13 #Python
You might like
PHP explode()函数用法、切分字符串
2012/10/03 PHP
php实现粘贴截图并完成上传功能
2015/05/17 PHP
谈谈php对接芝麻信用踩的坑
2016/12/01 PHP
PHP-CGI远程代码执行漏洞分析与防范
2017/05/07 PHP
PHP的curl函数的用法总结
2019/02/14 PHP
MacOS下PHP7.1升级到PHP7.4.15的方法
2021/02/22 PHP
用JavaScript事件串连执行多个处理过程的方法
2007/03/09 Javascript
javascript 学习之旅 (2)
2009/02/05 Javascript
JavaScript获取网页中第一个链接ID的方法
2015/04/03 Javascript
Javascript实现计算个人所得税
2015/05/10 Javascript
JavaScript中数据结构与算法(五):经典KMP算法
2015/06/19 Javascript
通过图带你深入了解vue的响应式原理
2019/06/21 Javascript
vue 保留两位小数 不能直接用toFixed(2) 的解决
2020/08/07 Javascript
python中使用OpenCV进行人脸检测的例子
2014/04/18 Python
Python中os和shutil模块实用方法集锦
2014/05/13 Python
python实现合并两个数组的方法
2015/05/16 Python
利用python操作SQLite数据库及文件操作详解
2017/09/22 Python
解决python3 pika之连接断开的问题
2018/12/18 Python
Python设计模式之适配器模式原理与用法详解
2019/01/15 Python
使用python3构建文件传输的方法
2019/02/13 Python
Python脚本按照当前日期创建多级目录
2019/03/01 Python
python 字符串常用函数详解
2019/09/11 Python
一篇文章教你用python画动态爱心表白
2020/11/22 Python
html5适合移动应用开发的12大特性
2014/03/19 HTML / CSS
业务部经理岗位职责
2014/01/04 职场文书
优秀干部获奖感言
2014/01/31 职场文书
财务科科长岗位职责
2014/03/10 职场文书
民族学专业大学生职业规划范文:清晰未来的构想
2014/09/20 职场文书
“向国旗敬礼”活动策划方案(4篇)
2014/09/27 职场文书
接待员岗位职责
2015/02/13 职场文书
开会通知短信大全
2015/04/20 职场文书
2015法院个人工作总结范文
2015/05/25 职场文书
宝葫芦的秘密观后感
2015/06/11 职场文书
尊师重教主题班会
2015/08/14 职场文书
基于Nginx实现限制某IP短时间访问次数
2021/03/31 Servers
Java常用工具类汇总 附示例代码
2021/06/26 Java/Android