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 Property属性的2种用法
Jun 21 Python
Python 模拟员工信息数据库操作的实例
Oct 23 Python
如何使用 Pylint 来规范 Python 代码风格(来自IBM)
Apr 06 Python
python实现在IDLE中输入多行的方法
Apr 19 Python
python机器学习之KNN分类算法
Aug 29 Python
python向字符串中添加元素的实例方法
Jun 28 Python
Python with标签使用方法解析
Jan 17 Python
tensorflow生成多个tfrecord文件实例
Feb 17 Python
如何基于python对接钉钉并获取access_token
Apr 21 Python
Python unittest单元测试openpyxl实现过程解析
May 27 Python
Java多线程实现四种方式原理详解
Jun 02 Python
Python Flask搭建yolov3目标检测系统详解流程
Nov 07 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将数据库中所有内容生成静态html文档的代码
2010/04/12 PHP
php绘制圆形的方法
2015/01/24 PHP
Thinkphp整合微信支付功能
2016/12/14 PHP
html读出文本文件内容
2007/01/22 Javascript
网页javascript精华代码集
2007/01/24 Javascript
鼠标滑上去后图片放大浮出效果的js代码
2011/05/28 Javascript
formValidator3.3的ajaxValidator一些异常分析
2011/07/12 Javascript
js有序数组的连接问题
2013/10/01 Javascript
JQuery控制radio选中和不选中方法总结
2015/04/15 Javascript
JQuery用户名校验的具体实现
2016/03/18 Javascript
无需 Flash 使用 jQuery 复制文字到剪贴板
2016/04/26 Javascript
浅谈jQuery 选择器和dom操作
2016/06/07 Javascript
jQuery实现的导航下拉菜单效果
2016/07/04 Javascript
JavaScript判断数组是否存在key的简单实例
2016/08/03 Javascript
React实现点击删除列表中对应项
2017/01/10 Javascript
浅谈javascript的闭包
2017/01/23 Javascript
javascript事件的传播基础实例讲解(35)
2017/02/14 Javascript
vue脚手架及vue-router基本使用
2018/04/09 Javascript
JS实现十分钟倒计时代码实例
2018/10/18 Javascript
antd Upload 文件上传的示例代码
2018/12/14 Javascript
微信小程序 wx.getUserInfo引导用户授权问题实例分析
2020/03/09 Javascript
Openlayers3实现车辆轨迹回放功能
2020/09/29 Javascript
[03:03]DOTA2校园争霸赛 济南城市决赛欢乐发奖活动
2013/10/21 DOTA
Python中的自定义函数学习笔记
2014/09/23 Python
Python 使用requests模块发送GET和POST请求的实现代码
2016/09/21 Python
python 读取txt中每行数据,并且保存到excel中的实例
2018/04/29 Python
Python对象中__del__方法起作用的条件详解
2018/11/01 Python
python笔记之mean()函数实现求取均值的功能代码
2019/07/05 Python
python读取ini配置文件过程示范
2019/12/23 Python
Python双链表原理与实现方法详解
2020/02/22 Python
python 实现一个简单的线性回归案例
2020/12/17 Python
萌新HTML5 入门指南(二)
2020/11/09 HTML / CSS
写求职信要注意什么问题
2014/04/12 职场文书
银行授权委托书范本
2014/10/04 职场文书
大学生村官工作总结2015
2015/04/09 职场文书
使用canvas仿Echarts实现金字塔图的实例代码
2021/11/11 HTML / CSS