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设置检查点简单实现代码
Jul 01 Python
Python连接DB2数据库
Aug 27 Python
利用python程序生成word和PDF文档的方法
Feb 14 Python
Python实现的爬取网易动态评论操作示例
Jun 06 Python
Python爬虫实现简单的爬取有道翻译功能示例
Jul 13 Python
python将txt文档每行内容循环插入数据库的方法
Dec 28 Python
使用 Python 玩转 GitHub 的贡献板(推荐)
Apr 04 Python
Python面向对象中类(class)的简单理解与用法分析
Feb 21 Python
Jupyter Notebook 实现正常显示中文和负号
Apr 24 Python
Django中的JWT身份验证的实现
May 07 Python
Pycharm 如何设置HTML文件自动补全代码或标签
May 21 Python
python中 Flask Web 表单的使用方法
May 20 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
一些星际专用术语解释
2020/03/04 星际争霸
深入PHP变量存储的详解
2013/06/13 PHP
php通过排列组合实现1到9数字相加都等于20的方法
2015/08/03 PHP
PHP Smarty模版简单使用方法
2016/03/30 PHP
Laravel中任务调度console使用方法小结
2017/05/07 PHP
根据对象的某一属性进行排序的js代码(如:name,age)
2010/08/10 Javascript
用队列模拟jquery的动画算法实例
2015/01/20 Javascript
JavaScript的jQuery库中ready方法的学习教程
2015/08/14 Javascript
跟我学习javascript的定时器
2015/11/19 Javascript
js实现可键盘控制的简单抽奖程序
2016/07/13 Javascript
Javascript中indexOf()和lastIndexOf应用方法实例
2016/08/24 Javascript
使用vue编写一个点击数字计时小游戏
2016/08/31 Javascript
微信小程序开发(一) 微信登录流程详解
2017/01/11 Javascript
基于Vue实现后台系统权限控制的示例代码
2017/08/29 Javascript
JavaScript中正则表达式使数字、中文或指定字符高亮显示
2017/10/31 Javascript
vue设置导航栏、侧边栏为公共页面的例子
2019/11/01 Javascript
从零学python系列之新版本导入httplib模块报ImportError解决方案
2014/05/23 Python
跟老齐学Python之坑爹的字符编码
2014/09/28 Python
python连接oracle数据库实例
2014/10/17 Python
利用Python进行异常值分析实例代码
2017/12/07 Python
Python3.7中安装openCV库的方法
2018/07/11 Python
pytorch: tensor类型的构建与相互转换实例
2018/07/26 Python
python3.7.0的安装步骤
2018/08/27 Python
python pygame模块编写飞机大战
2018/11/20 Python
Python可变和不可变、类的私有属性实例分析
2019/05/31 Python
Python编程快速上手——strip()函数的正则表达式实现方法分析
2020/02/29 Python
Python实现进度条和时间预估的示例代码
2020/06/02 Python
python3将变量输入的简单实例
2020/08/19 Python
详解background属性的8个属性值(面试题)
2020/11/02 HTML / CSS
2014年圣诞节倒计时网页的制作过程
2014/12/05 HTML / CSS
Mountain Warehouse澳大利亚官网:欧洲家庭户外品牌倡导者
2016/11/20 全球购物
欧缇丽加拿大官方网站:Caudalie加拿大
2019/07/18 全球购物
普通大学毕业生自荐信
2013/11/04 职场文书
安全施工责任书
2014/08/25 职场文书
单位婚育证明范本
2014/11/21 职场文书
中学综治宣传月活动总结
2015/05/07 职场文书