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搭建微信公众平台
Feb 16 Python
Linux CentOS7下安装python3 的方法
Jan 21 Python
Python迭代器与生成器用法实例分析
Jul 09 Python
Python爬虫框架Scrapy常用命令总结
Jul 26 Python
python看某个模块的版本方法
Oct 16 Python
解决安装python库时windows error5 报错的问题
Oct 21 Python
Python 实现子类获取父类的类成员方法
Jan 11 Python
利用Python半自动化生成Nessus报告的方法
Mar 19 Python
Django使用redis缓存服务器的实现代码示例
Apr 28 Python
python下对hsv颜色空间进行量化操作
Jun 04 Python
Python和Bash结合在一起的方法
Nov 13 Python
OpenCV全景图像拼接的实现示例
Jun 05 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服务器实现多session并发运行
2006/10/09 PHP
php5.3中连接sqlserver2000的两种方法(com与ODBC)
2012/12/29 PHP
javascript 哈希表(hashtable)的简单实现
2010/01/20 Javascript
jquery中ajax学习笔记一
2011/10/16 Javascript
一个简单的Ext.XTemplate的实例代码
2012/03/18 Javascript
javascript实现焦点滚动图效果 具体方法
2013/06/24 Javascript
js 通用订单代码
2013/12/23 Javascript
用box固定长宽实现图片自动轮播js代码
2014/06/09 Javascript
jQuery实现的仿select功能代码
2015/08/19 Javascript
jQuery+HTML5美女瀑布流布局实现方法
2015/09/21 Javascript
如何防止JavaScript自动插入分号
2015/11/05 Javascript
AngularJS模板加载用法详解
2016/11/04 Javascript
vuejs开发组件分享之H5图片上传、压缩及拍照旋转的问题处理
2017/03/06 Javascript
bootstrap table动态加载数据示例代码
2017/03/25 Javascript
node.js平台下利用cookie实现记住密码登陆(Express+Ejs+Mysql)
2017/04/26 Javascript
Angular2使用jQuery的方法教程
2017/05/28 jQuery
vue下跨域设置的相关介绍
2017/08/26 Javascript
vue.js的computed,filter,get,set的用法及区别详解
2018/03/08 Javascript
Angular2中监听数据更新的方法
2018/08/31 Javascript
基于JavaScript 实现拖放功能
2019/09/12 Javascript
在vue+element ui框架里实现lodash的debounce防抖
2019/11/13 Javascript
vue.js实现h5机器人聊天(测试版)
2020/07/16 Javascript
Python计算开方、立方、圆周率,精确到小数点后任意位的方法
2018/07/17 Python
详解python中TCP协议中的粘包问题
2019/03/22 Python
美国家具网站:Cymax
2016/09/17 全球购物
SOA面试题:如何在SOA中实现松耦合
2013/07/21 面试题
音乐专业应届生教师求职信
2013/11/04 职场文书
军校制空专业毕业生自我鉴定
2013/11/16 职场文书
领导接待方案
2014/03/13 职场文书
学习型党组织心得体会
2014/09/12 职场文书
工作检讨书大全
2015/01/26 职场文书
音乐教师求职信范文
2015/03/20 职场文书
三八妇女节新闻稿
2015/07/17 职场文书
继续教育心得体会(共6篇)
2016/01/19 职场文书
Python手拉手教你爬取贝壳房源数据的实战教程
2021/05/21 Python
MySQL 字符集 character
2022/05/04 MySQL