python函数装饰器用法实例详解


Posted in Python onJune 04, 2015

本文实例讲述了python函数装饰器用法。分享给大家供大家参考。具体如下:

装饰器经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,
有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

#! coding=utf-8 
import time 
def timeit(func): 
  def wrapper(a): 
    start = time.clock() 
    func(1,2) 
    end =time.clock() 
    print 'used:', end - start 
    print a 
  return wrapper 
@timeit
# foo = timeit(foo)完全等价, 
# 使用之后,foo函数就变了,相当于是wrapper了 
def foo(a,b): 
  pass 
#不带参数的装饰器 
# wraper 将fn进行装饰,return wraper ,返回的wraper 就是装饰之后的fn 
def test(func): 
  def wraper(): 
    print "test start" 
    func() 
    print "end start" 
  return wraper 
@test 
def foo(): 
  print "in foo" 
foo()

输出:

test start 
in foo 
end start

装饰器修饰带参数的函数:

def parameter_test(func): 
  def wraper(a): 
    print "test start" 
    func(a) 
    print "end start" 
  return wraper 
@parameter_test 
def parameter_foo(a): 
  print "parameter_foo:"+a 
#parameter_foo('hello')

输出:

>>> 
test start 
parameter_foo:hello 
end start

装饰器修饰不确定参数个数的函数:

def much_test(func): 
  def wraper(*args, **kwargs): 
    print "test start" 
    func(*args, **kwargs) 
    print "end start" 
  return wraper 
@much_test 
def much1(a): 
  print a 
@much_test 
def much2(a,b,c,d ): 
  print a,b,c,d 
much1('a') 
much2(1,2,3,4)

输出:

test start 
a 
end start 
test start 
1 2 3 4 
end start

带参数的装饰器,再包一层就可以了:

def tp(name,age): 
  def much_test(func): 
    print 'in much_test' 
    def wraper(*args, **kwargs): 
      print "test start" 
      print str(name),'at:'+str(age) 
      func(*args, **kwargs) 
      print "end start" 
    return wraper 
  return much_test 
@tp('one','10') 
def tpTest(parameter): 
  print parameter 
tpTest('python....')

输出:

in much_test 
test start 
one at:10 
python.... 
end start
class locker: 
  def __init__(self): 
    print("locker.__init__() should be not called.") 
  @staticmethod 
  def acquire(): 
    print("locker.acquire() called.(这是静态方法)") 
  @staticmethod 
  def release(): 
    print("locker.release() called.(不需要对象实例") 
def deco(cls): 
  '''cls 必须实现acquire和release静态方法''' 
  def _deco(func): 
    def __deco(): 
      print("before %s called [%s]." % (func.__name__, cls)) 
      cls.acquire() 
      try: 
        return func() 
      finally: 
        cls.release() 
    return __deco 
  return _deco 
@deco(locker) 
def myfunc(): 
  print(" myfunc() called.") 
myfunc()

输出:

>>> 
before myfunc called [__main__.locker].
locker.acquire() called.(这是静态方法)
 myfunc() called.
locker.release() called.(不需要对象实例
>>>
class mylocker: 
  def __init__(self): 
    print("mylocker.__init__() called.") 
  @staticmethod 
  def acquire(): 
    print("mylocker.acquire() called.") 
  @staticmethod 
  def unlock(): 
    print(" mylocker.unlock() called.") 
class lockerex(mylocker): 
  @staticmethod 
  def acquire(): 
    print("lockerex.acquire() called.") 
  @staticmethod 
  def unlock(): 
    print(" lockerex.unlock() called.") 
def lockhelper(cls): 
  '''cls 必须实现acquire和release静态方法''' 
  def _deco(func): 
    def __deco(*args, **kwargs): 
      print("before %s called." % func.__name__) 
      cls.acquire() 
      try: 
        return func(*args, **kwargs) 
      finally: 
        cls.unlock() 
    return __deco 
  return _deco 
class example: 
  @lockhelper(mylocker) 
  def myfunc(self): 
    print(" myfunc() called.") 
  @lockhelper(mylocker) 
  @lockhelper(lockerex) 
  def myfunc2(self, a, b): 
    print(" myfunc2() called.") 
    return a + b 
if __name__=="__main__": 
  a = example() 
  a.myfunc() 
  print(a.myfunc()) 
  print(a.myfunc2(1, 2)) 
  print(a.myfunc2(3, 4))

输出:

before myfunc called.
mylocker.acquire() called.
 myfunc() called.
 mylocker.unlock() called.
before myfunc called.
mylocker.acquire() called.
 myfunc() called.
 mylocker.unlock() called.
None
before __deco called.
mylocker.acquire() called.
before myfunc2 called.
lockerex.acquire() called.
 myfunc2() called.
 lockerex.unlock() called.
 mylocker.unlock() called.
3
before __deco called.
mylocker.acquire() called.
before myfunc2 called.
lockerex.acquire() called.
 myfunc2() called.
 lockerex.unlock() called.
 mylocker.unlock() called.
7

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
在Python中使用sort()方法进行排序的简单教程
May 21 Python
Python求出0~100以内的所有素数
Jan 23 Python
python获取指定字符串中重复模式最高的字符串方法
Jun 29 Python
pyQT5 实现窗体之间传值的示例
Jun 20 Python
Python Web框架之Django框架Form组件用法详解
Aug 16 Python
Django模板语言 Tags使用详解
Sep 09 Python
Python使用random模块生成随机数操作实例详解
Sep 17 Python
对Pytorch中Tensor的各种池化操作解析
Jan 03 Python
django正续或者倒序查库实例
May 19 Python
tensorflow 2.1.0 安装与实战教程(CASIA FACE v5)
Jun 30 Python
Pytest单元测试框架如何实现参数化
Sep 05 Python
python用分数表示矩阵的方法实例
Jan 11 Python
Python中函数的参数定义和可变参数用法实例分析
Jun 04 #Python
python类装饰器用法实例
Jun 04 #Python
python获得一个月有多少天的方法
Jun 04 #Python
Python中threading模块join函数用法实例分析
Jun 04 #Python
django通过ajax发起请求返回JSON格式数据的方法
Jun 04 #Python
python创建进程fork用法
Jun 04 #Python
Python文件及目录操作实例详解
Jun 04 #Python
You might like
php事务处理实例详解
2014/07/11 PHP
Laravel 5框架学习之数据库迁移(Migrations)
2015/04/08 PHP
PHP多种序列化/反序列化的方法详解
2017/06/23 PHP
PHP addAttribute()函数讲解
2019/02/03 PHP
PHP接口类(interface)的定义、特点和应用示例
2020/05/18 PHP
Javascript selection的兼容性写法介绍
2013/12/20 Javascript
jQuery文件上传插件Uploadify使用指南
2014/06/05 Javascript
分享一个自己动手写的jQuery分页插件
2014/08/28 Javascript
jQuery实现“扫码阅读”功能
2015/01/21 Javascript
Javascript实现快速排序(Quicksort)的算法详解
2015/09/06 Javascript
Vue项目中quill-editor带样式编辑器的使用方法
2017/08/08 Javascript
Vue组件的使用教程详解
2018/01/05 Javascript
深入理解react-router 路由的实现原理
2018/09/26 Javascript
WebGL学习教程之Three.js学习笔记(第一篇)
2019/04/25 Javascript
vue slot与传参实例代码讲解
2019/04/28 Javascript
JavaScript判断浏览器运行环境的详细方法
2019/06/30 Javascript
js中的this的指向问题详解
2019/08/29 Javascript
js中switch语句的学习笔记
2020/03/25 Javascript
js用正则表达式筛选年月日的实例方法
2021/01/04 Javascript
[55:26]DOTA2-DPC中国联赛 正赛 Aster vs LBZS BO3 第一场 2月23日
2021/03/11 DOTA
python中urllib模块用法实例详解
2014/11/19 Python
Python实现的多线程端口扫描工具分享
2015/01/21 Python
python用来获得图片exif信息的库实例分析
2015/03/16 Python
详解Python3中yield生成器的用法
2015/08/20 Python
在windows下快速搭建web.py开发框架方法
2016/04/22 Python
python将一个英文语句以单词为单位逆序排放的方法
2018/12/20 Python
pyqt5 QProgressBar清空进度条的实例
2019/06/21 Python
PowerBI和Python关于数据分析的对比
2019/07/11 Python
python django model联合主键的例子
2019/08/06 Python
中国电子产品外贸网站:MiniIntheBox
2017/02/06 全球购物
工程力学专业毕业生求职信
2013/10/06 职场文书
会计主管岗位职责
2014/01/03 职场文书
学生出入校管理制度
2014/01/16 职场文书
创业计划书模版
2014/02/05 职场文书
css背景和边框标签实例详解
2021/05/21 HTML / CSS
vue配置型表格基于el-table拓展之table-plus组件
2022/04/12 Vue.js