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 运算符 供重载参考
Jun 11 Python
python实现的udp协议Server和Client代码实例
Jun 04 Python
在Python中使用poplib模块收取邮件的教程
Apr 29 Python
Python3通过Luhn算法快速验证信用卡卡号的方法
May 14 Python
Python实现监控程序执行时间并将其写入日志的方法
Jun 30 Python
Python 常用string函数详解
May 30 Python
python实现守护进程、守护线程、守护非守护并行
May 05 Python
python 删除excel表格重复行,数据预处理操作
Jul 06 Python
从python读取sql的实例方法
Jul 21 Python
pandas 操作 Excel操作总结
Mar 31 Python
python使用openpyxl库读写Excel表格的方法(增删改查操作)
May 02 Python
Python 统计序列中元素的出现频度
Apr 26 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字符转义相关函数小结(php下的转义字符串)
2007/04/12 PHP
php strcmp使用说明
2010/04/22 PHP
PHP 设计模式系列之 specification规格模式
2016/01/10 PHP
老司机传授Ubuntu下Apache+PHP+MySQL环境搭建攻略
2016/03/20 PHP
js实现拖拽 闭包函数详细介绍
2012/11/25 Javascript
javascript 利用Image对象实现的埋点(某处的点击数)统计
2012/12/28 Javascript
jQuery 处理页面的事件详解
2015/01/20 Javascript
超详细的javascript数组方法汇总
2015/11/21 Javascript
javascript简单实现跟随滚动条漂浮的返回顶部按钮效果
2016/08/19 Javascript
Javascript中Promise的四种常用方法总结
2017/07/14 Javascript
jquery easyui如何实现格式化列
2017/07/30 jQuery
快速搭建React的环境步骤详解
2017/11/06 Javascript
angular4笔记系列之内置指令小结
2018/11/09 Javascript
原生js实现移动端Touch轮播图的方法步骤
2019/01/03 Javascript
create-react-app使用antd按需加载的样式无效问题的解决
2019/02/26 Javascript
微信小程序template模板与component组件的区别和使用详解
2019/05/22 Javascript
Python struct模块解析
2014/06/12 Python
python list是否包含另一个list所有元素的实例
2018/05/04 Python
python MNIST手写识别数据调用API的方法
2018/08/08 Python
Python中__slots__属性介绍与基本使用方法
2018/09/05 Python
通过python的matplotlib包将Tensorflow数据进行可视化的方法
2019/01/09 Python
python可视化实现代码
2019/01/15 Python
numpy concatenate数组拼接方法示例介绍
2019/05/27 Python
python异步实现定时任务和周期任务的方法
2019/06/29 Python
Python3安装pip工具的详细步骤
2019/10/14 Python
Python中join()函数多种操作代码实例
2020/01/13 Python
numpy 矩阵形状调整:拉伸、变成一位数组的实例
2020/06/18 Python
matplotlib制作雷达图报错ValueError的实现
2021/01/05 Python
numba提升python运行速度的实例方法
2021/01/25 Python
CSS3 不定高宽垂直水平居中的几种方式
2020/03/26 HTML / CSS
世界上最大的在线汽车租赁预订平台:Rentalcars.com(支持中文)
2018/10/12 全球购物
Moda Operandi官网:美国奢侈品电商,海淘秀场T台同款
2020/05/26 全球购物
餐饮食品安全责任书
2015/01/29 职场文书
社区义诊通知
2015/04/24 职场文书
中学语文教学反思
2016/02/16 职场文书
我对PyTorch dataloader里的shuffle=True的理解
2021/05/20 Python