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实现统计代码行数的方法
May 22 Python
python中使用print输出中文的方法
Jul 16 Python
Python使用random.shuffle()打乱列表顺序的方法
Nov 08 Python
python区块及区块链的开发详解
Jul 03 Python
Python-Flask:动态创建表的示例详解
Nov 22 Python
python 实现让字典的value 成为列表
Dec 16 Python
Python描述符descriptor使用原理解析
Mar 21 Python
pycharm2020.2 配置使用的方法详解
Sep 16 Python
Python模块常用四种安装方式
Oct 20 Python
Python系统公网私网流量监控实现流程
Nov 23 Python
django项目中使用云片网发送短信验证码的实现
Jan 19 Python
Python 如何解决稀疏矩阵运算
May 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
php 文件夹删除、php清除缓存程序
2009/08/25 PHP
深入解析PHP底层机制及相关原理
2020/12/11 PHP
jQuery+ajax实现顶一下,踩一下效果
2010/07/17 Javascript
jQuery 瀑布流 浮动布局(一)(延迟AJAX加载图片)
2012/05/23 Javascript
js onkeypress与onkeydown 事件区别详细说明
2012/12/13 Javascript
浅析js中2个等号与3个等号的区别
2013/08/06 Javascript
jQuery实现鼠标划过修改样式的方法
2015/04/14 Javascript
用jquery获取自定义的标签属性的值简单实例
2016/09/17 Javascript
JavaScript仿百度图片浏览效果
2016/11/23 Javascript
javascript事件捕获机制【深入分析IE和DOM中的事件模型】
2016/12/15 Javascript
codeMirror插件使用讲解
2017/01/16 Javascript
详解JS中遍历语法的比较
2017/04/07 Javascript
JavaScript实现前端分页控件
2017/04/19 Javascript
Angular 4依赖注入学习教程之ValueProvider的使用(七)
2017/06/04 Javascript
js实现登录注册框手机号和验证码校验(前端部分)
2017/09/28 Javascript
vue自定义指令之面板拖拽的实现
2019/04/14 Javascript
Vue-CLI项目中路由传参的方式详解
2019/09/01 Javascript
js实现时分秒倒计时
2019/12/03 Javascript
vue倒计时刷新页面不会从头开始的解决方法
2020/03/03 Javascript
解决vue bus.$emit触发第一次$on监听不到问题
2020/07/28 Javascript
Python数据结构与算法之二叉树结构定义与遍历方法详解
2017/12/12 Python
Django分页查询并返回jsons数据(中文乱码解决方法)
2018/08/02 Python
python爬取指定微信公众号文章
2018/12/20 Python
Python使用enumerate获取迭代元素下标
2020/02/03 Python
PyTorch的torch.cat用法
2020/06/28 Python
Python WebSocket长连接心跳与短连接的示例
2020/11/24 Python
Molton Brown美国官网:奢华美容、香水、沐浴和身体护理
2020/09/02 全球购物
shell的种类有哪些
2015/04/15 面试题
会计自我鉴定范文
2013/10/06 职场文书
应届生英语教师求职信
2013/11/05 职场文书
揭牌仪式主持词
2014/03/19 职场文书
经典安踏广告词
2014/03/21 职场文书
七匹狼男装广告词
2014/03/21 职场文书
工资收入证明
2014/10/07 职场文书
旷工检讨书1000字
2015/01/01 职场文书
MYSQL 表的全面总结
2021/11/11 MySQL