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 相关文章推荐
详解Python3中的Sequence type的使用
Aug 01 Python
Python提取网页中超链接的方法
Sep 18 Python
Django返回json数据用法示例
Sep 18 Python
win系统下为Python3.5安装flask-mongoengine 库
Dec 20 Python
如何在django里上传csv文件并进行入库处理的方法
Jan 02 Python
python模拟菜刀反弹shell绕过限制【推荐】
Jun 25 Python
对python 中re.sub,replace(),strip()的区别详解
Jul 22 Python
基于Python实现大文件分割和命名脚本过程解析
Sep 29 Python
Python3和PyCharm安装与环境配置【图文教程】
Feb 14 Python
Django调用支付宝接口代码实例详解
Apr 04 Python
Python代码注释规范代码实例解析
Aug 14 Python
Python:__eq__和__str__函数的使用示例
Sep 26 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
输出控制类
2006/10/09 PHP
ThinkPHP模板判断输出Empty标签用法详解
2014/06/30 PHP
PHP编写登录验证码功能 附调用方法
2016/05/19 PHP
Thinkphp5框架异常处理操作实例分析
2020/06/03 PHP
TNC vs IO BO3 第二场2.13
2021/03/10 DOTA
基于jquery实现漂亮的动态信息提示效果
2011/08/02 Javascript
分享一个我自己写的ToolTip提示插件(附源码)
2013/01/20 Javascript
使用CSS和jQuery模拟select并附提交后取得数据的代码
2013/10/18 Javascript
JavaScript DOM操作表格及样式
2015/04/13 Javascript
asp.net中oracle 存储过程(图文)
2015/08/12 Javascript
详解Angular的内置过滤器和自定义过滤器【推荐】
2016/12/26 Javascript
vue中Npm run build 根据环境传递参数方法来打包不同域名
2018/03/29 Javascript
vue中设置、获取、删除cookie的方法
2018/09/21 Javascript
Python的Django框架中的Context使用
2015/07/15 Python
Python使用matplotlib绘制多个图形单独显示的方法示例
2018/03/14 Python
python打包压缩、读取指定目录下的指定类型文件
2018/04/12 Python
tensorflow更改变量的值实例
2018/07/30 Python
python2.7和NLTK安装详细教程
2018/09/19 Python
使用Python制作简单的小程序IP查看器功能
2019/04/16 Python
python正则表达式的懒惰匹配和贪婪匹配说明
2020/07/13 Python
python使用matplotlib:subplot绘制多个子图的示例
2020/09/24 Python
css3实现的下拉菜单效果示例
2014/01/22 HTML / CSS
用HTML5制作一个简单的桌球游戏的教程
2015/05/12 HTML / CSS
函授毕业自我鉴定
2014/02/04 职场文书
护理专科自荐书范文
2014/02/18 职场文书
高中军训感言200字
2014/02/23 职场文书
优秀团干部个人事迹
2014/05/29 职场文书
本科毕业生应聘自荐信范文
2014/06/26 职场文书
初中生毕业评语
2014/12/29 职场文书
专业技术人员年度考核评语
2014/12/31 职场文书
论文致谢词范文
2015/05/14 职场文书
2015年银行信贷员工作总结
2015/05/19 职场文书
2015医院个人工作总结范文
2015/05/21 职场文书
2016年三严三实党课学习心得体会
2016/01/06 职场文书
生鲜超市—未来中国最具有潜力零售业态
2019/08/02 职场文书
Shell脚本一键安装Nginx服务自定义Nginx版本
2022/03/20 Servers