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中的Queue与多进程
Aug 25 Python
python正则表达式的使用
Jun 12 Python
Python实现Pig Latin小游戏实例代码
Feb 02 Python
详解PyCharm配置Anaconda的艰难心路历程
Aug 13 Python
简单了解python中对象的取反运算符
Jul 01 Python
python UDP(udp)协议发送和接收的实例
Jul 22 Python
python迭代器常见用法实例分析
Nov 22 Python
Django多数据库配置及逆向生成model教程
Mar 28 Python
在Keras中CNN联合LSTM进行分类实例
Jun 29 Python
Python如何将字符串转换为日期
Jul 31 Python
python调用jenkinsAPI构建jenkins,并传递参数的示例
Dec 09 Python
解决jupyter notebook启动后没有token的坑
Apr 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获取英文姓名首字母的方法
2015/07/13 PHP
PHP获取文件扩展名的4种方法
2015/11/24 PHP
Laravel实现自定义错误输出内容的方法
2016/10/10 PHP
如何判断php mysqli扩展类是否开启
2016/12/24 PHP
php 猴子摘桃的算法
2017/06/20 PHP
javascript编程起步(第二课)
2007/01/10 Javascript
完美兼容IE,chrome,ff的设为首页、加入收藏及保存到桌面js代码
2014/12/17 Javascript
基于javascript实现仿百度输入框自动匹配功能
2016/01/03 Javascript
利用vue-router实现二级菜单内容转换
2016/11/30 Javascript
jquery删除数组中重复元素
2016/12/05 Javascript
原生ajax处理json格式数据的实例代码
2016/12/25 Javascript
详解用vue编写弹出框组件
2017/07/04 Javascript
vue.js实现点击后动态添加class及删除同级class的实现代码
2018/04/04 Javascript
微信小程序textarea层级过高的解决方法
2019/03/04 Javascript
node.js监听文件变化的实现方法
2019/04/17 Javascript
RxJS的入门指引和初步应用
2019/06/15 Javascript
vue filter 完美时间日期格式的代码
2019/08/14 Javascript
json解析大全 双引号、键值对不在一起的情况
2019/12/06 Javascript
Python中支持向量机SVM的使用方法详解
2017/12/26 Python
python实现简单淘宝秒杀功能
2018/05/03 Python
tensorflow: 查看 tensor详细数值方法
2018/06/13 Python
Python 3.x 判断 dict 是否包含某键值的实例讲解
2018/07/06 Python
Python实现的各种常见分布算法示例
2018/12/13 Python
python 中的列表生成式、生成器表达式、模块导入
2019/06/19 Python
python的sys.path模块路径添加方式
2020/03/09 Python
PyCharm安装PyQt5及其工具(Qt Designer、PyUIC、PyRcc)的步骤详解
2020/11/02 Python
python os.rename实例用法详解
2020/12/06 Python
CSS3 简写animation
2012/05/10 HTML / CSS
美国皮靴公司自1863年:The Frye Company
2016/11/30 全球购物
财经学院自荐信范文
2014/02/02 职场文书
初级会计求职信范文
2014/02/15 职场文书
中文教师求职信
2014/02/22 职场文书
法学专业求职信
2014/07/15 职场文书
孔子观后感
2015/06/08 职场文书
创业计划书之面包店
2019/09/12 职场文书
JavaScript嵌入百度地图API的最详细方法
2021/04/16 Javascript