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设置socket代理的方法
Jan 14 Python
Python中使用第三方库xlrd来写入Excel文件示例
Apr 05 Python
Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享
Jul 04 Python
Python的SQLalchemy模块连接与操作MySQL的基础示例
Jul 11 Python
python3使用pyqt5制作一个超简单浏览器的实例
Oct 19 Python
详细分析python3的reduce函数
Dec 05 Python
python抓取网页内容并进行语音播报的方法
Dec 24 Python
使用 Python 玩转 GitHub 的贡献板(推荐)
Apr 04 Python
使用python爬取微博数据打造一颗“心”
Jun 28 Python
Python传递参数的多种方式(小结)
Sep 18 Python
ansible动态Inventory主机清单配置遇到的坑
Jan 19 Python
python matplotlib绘制三维图的示例
Sep 24 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中实现方案
2012/11/02 PHP
PHP模板解析类实例
2015/07/09 PHP
Laravel框架实现利用监听器进行sql语句记录功能
2018/06/06 PHP
TP5框架使用QueryList采集框架爬小说操作示例
2020/03/26 PHP
PHP7 弃用功能
2021/03/09 PHP
获取JavaScript用户自定义类的类名称的代码
2007/03/08 Javascript
基础的prototype.js常用函数及其用法
2007/03/10 Javascript
JS面向对象编程 for Cookie
2010/09/19 Javascript
Web 前端设计模式--Dom重构 提高显示性能
2010/10/22 Javascript
jQuery中json对象的复制方式介绍(数组及对象)
2013/06/08 Javascript
Javascript中数组sort和reverse用法分析
2014/12/30 Javascript
微信小程序 绘图之饼图实现
2016/10/24 Javascript
JS回调函数基本定义与用法实例分析
2017/05/24 Javascript
微信小程序商品到详情的实现
2017/06/27 Javascript
Vue2.0 vue-source jsonp 跨域请求
2017/08/04 Javascript
Vue.js自定义事件的表单输入组件方法
2018/03/08 Javascript
jquery引入外部CDN 加载失败则引入本地jq库
2018/05/23 jQuery
React 实现车牌键盘的示例代码
2019/12/20 Javascript
Python爬取十篇新闻统计TF-IDF
2018/01/03 Python
Python之reload流程实例代码解析
2018/01/29 Python
Python定义一个跨越多行的字符串的多种方法小结
2018/07/19 Python
matplotlib.pyplot绘图显示控制方法
2019/01/15 Python
python并发爬虫实用工具tomorrow实用解析
2019/09/25 Python
Python 取numpy数组的某几行某几列方法
2019/10/24 Python
python利用google翻译方法实例(翻译字幕文件)
2020/09/21 Python
Python3 用matplotlib绘制sigmoid函数的案例
2020/12/11 Python
丝芙兰意大利官方网站:Sephora.it
2019/12/13 全球购物
资深财务管理人员自我评价
2013/09/22 职场文书
超市后勤自我鉴定
2014/01/17 职场文书
商场促销活动方案
2014/02/08 职场文书
小摄影师教学反思
2014/04/27 职场文书
2015年团支书工作总结
2015/04/03 职场文书
幼儿园开学报名通知
2015/07/16 职场文书
承诺书怎么写 ?
2019/04/16 职场文书
Apache Hudi的多版本清理服务彻底讲解
2022/03/31 Servers
MySql如何将查询的出来的字段进行转换
2022/06/14 MySQL