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 相关文章推荐
go和python调用其它程序并得到程序输出
Feb 10 Python
Python内置的HTTP协议服务器SimpleHTTPServer使用指南
Mar 30 Python
Python代码实现KNN算法
Dec 20 Python
Python2实现的图片文本识别功能详解
Jul 11 Python
python实现对指定字符串补足固定长度倍数截断输出的方法
Nov 15 Python
使用python-opencv读取视频,计算视频总帧数及FPS的实现
Dec 10 Python
python关闭占用端口方式
Dec 17 Python
用python拟合等角螺线的实现示例
Dec 27 Python
在echarts中图例legend和坐标系grid实现左右布局实例
May 16 Python
常用的10个Python实用小技巧
Aug 10 Python
Python页面加载的等待方式总结
Feb 28 Python
彻底解决pip下载pytorch慢的问题方法
Mar 01 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 5.3.x 的strtotime() 时区设定 警告信息修复
2013/08/05 PHP
jQuery Mobile + PHP实现文件上传
2014/12/12 PHP
PHP数组函数array_multisort()用法实例分析
2016/04/02 PHP
PHP基于socket实现客户端和服务端通讯功能
2017/07/13 PHP
js最简单的拖拽效果实现代码
2010/09/24 Javascript
使用Math.floor与Math.random取随机整数的方法详解
2013/05/07 Javascript
javascript伸缩型菜单实现代码
2015/11/16 Javascript
谈一谈js中的执行环境及作用域
2016/03/30 Javascript
JS实现PC手机端和嵌入式滑动拼图验证码三种效果
2017/02/15 Javascript
Angular 4依赖注入学习教程之ClassProvider的使用(三)
2017/06/04 Javascript
将jquery.qqFace.js表情转换成微信的字符码
2017/12/01 jQuery
Vue引用第三方datepicker插件无法监听datepicker输入框的值的解决
2018/01/27 Javascript
Express本地测试HTTPS的示例代码
2018/06/06 Javascript
jQuery实现的鼠标拖动画矩形框示例【可兼容IE8】
2019/05/17 jQuery
微信小程序在线客服自动回复功能(基于node)
2019/07/03 Javascript
[00:39]DOTA2上海特级锦标赛 Liquid战队宣传片
2016/03/04 DOTA
Python切换pip安装源的方法详解
2016/11/18 Python
python使用正则表达式的search()函数实现指定位置搜索功能
2017/11/10 Python
详谈python中冒号与逗号的区别
2018/04/18 Python
Python爬虫之pandas基本安装与使用方法示例
2018/08/08 Python
python 的 scapy库,实现网卡收发包的例子
2019/07/23 Python
Python使用进程Process模块管理资源
2020/03/05 Python
python 进制转换 int、bin、oct、hex的原理
2021/01/13 Python
CSS3中各种颜色属性的使用教程
2016/05/17 HTML / CSS
马来西亚航空官方网站:Malaysia Airlines
2017/07/28 全球购物
阿联酋航空官方网站:Emirates
2017/10/17 全球购物
Omio俄罗斯:一次搜索公共汽车、火车和飞机的机票
2018/11/17 全球购物
瑞典度假品牌:OAS
2019/05/28 全球购物
公司道歉信范文
2014/01/09 职场文书
致长跑运动员广播稿
2014/01/31 职场文书
红旗方阵解说词
2014/02/12 职场文书
学校先进集体事迹材料
2014/05/31 职场文书
大学生应聘导游自荐信
2014/06/02 职场文书
停电调休通知
2015/04/16 职场文书
毕业典礼致辞
2015/07/29 职场文书
保险公司岗前培训工作总结
2015/10/24 职场文书