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深入学习之上下文管理器
Aug 31 Python
浅谈MySQL中的触发器
May 05 Python
Python中的下划线详解
Jun 24 Python
Python获取linux主机ip的简单实现方法
Apr 18 Python
python实现简易云音乐播放器
Jan 04 Python
Python中如何使用if语句处理列表实例代码
Feb 24 Python
python 判断linux进程,并杀死进程的实现方法
Jul 01 Python
Python常用模块sys,os,time,random功能与用法实例分析
Jan 07 Python
Python+OpenCV实现旋转文本校正方式
Jan 09 Python
TensorFlow设置日志级别的几种方式小结
Feb 04 Python
python 递归调用返回None的问题及解决方法
Mar 16 Python
keras.utils.to_categorical和one hot格式解析
Jul 02 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
第五节 克隆 [5]
2006/10/09 PHP
单点登录 Ucenter示例分析
2013/10/29 PHP
在PHP语言中使用JSON和将json还原成数组的方法
2016/07/19 PHP
php对微信支付回调处理的方法
2018/08/23 PHP
日期 时间js控件
2009/05/07 Javascript
在vs2010中调试javascript代码方法
2011/02/11 Javascript
jquery序列化表单去除指定元素示例代码
2014/04/10 Javascript
jQuery基础语法实例入门
2014/12/23 Javascript
JavaScript将一个数组插入到另一个数组的方法
2015/03/19 Javascript
JS模态窗口返回值兼容问题的完美解决方法
2016/05/28 Javascript
AngularJS 指令详细介绍
2016/07/27 Javascript
jQuery删除节点用法示例(remove方法)
2016/09/08 Javascript
jQuery通过ajax方法获取json数据不执行success的原因及解决方法
2016/10/15 Javascript
jQuery插件ImgAreaSelect实现头像上传预览和裁剪功能实例讲解一
2017/05/26 jQuery
浅谈vue路径优化之resolve
2017/10/13 Javascript
Vue组件开发之LeanCloud带图形校验码的短信发送功能
2017/11/07 Javascript
小程序实现多选框功能
2018/10/30 Javascript
Vue ​v-model相关知识总结
2021/01/28 Vue.js
python 判断一个进程是否存在
2009/04/09 Python
python BeautifulSoup设置页面编码的方法
2015/04/03 Python
Python中一行和多行import模块问题
2018/04/01 Python
python os.path模块常用方法实例详解
2018/09/16 Python
python重试装饰器的简单实现方法
2019/01/31 Python
简单了解python中对象的取反运算符
2019/07/01 Python
CSS Grid布局教程之网格单元格布局
2014/12/30 HTML / CSS
使用HTML5 Geolocation实现一个距离追踪器
2018/04/09 HTML / CSS
Bobbi Brown芭比波朗美国官网:化妆师专业彩妆保养品品牌
2016/08/18 全球购物
史蒂夫·马登加拿大官网:Steve Madden加拿大
2017/11/18 全球购物
激光脱毛、蓝光和护肤:Tria Beauty
2019/03/28 全球购物
Juice Beauty官网:有机美容产品,护肤与化妆品
2020/06/13 全球购物
c/c++某大公司的两道笔试题
2014/02/02 面试题
纪念建党演讲稿范文
2014/01/13 职场文书
校园文明标语
2014/06/13 职场文书
解除劳动关系协议书范文
2014/09/11 职场文书
致百米运动员广播稿5篇
2014/10/13 职场文书
什么是css原子化,有什么用?
2022/04/24 HTML / CSS