python函数装饰器用法实例详解

 更新时间:2015年06月04日 12:17:55   作者:MaxOmnis  
这篇文章主要介绍了python函数装饰器用法,以实例形式较为详细的分析了Python函数装饰器的常见使用技巧,需要的朋友可以参考下

本文实例讲述了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命令行参数argparse模块基本用法详解

    python命令行参数argparse模块基本用法详解

    argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数,这篇文章主要介绍了python命令行参数-argparse模块基本用法,需要的朋友可以参考下
    2023-01-01
  • 使用Python实现跳一跳自动跳跃功能

    使用Python实现跳一跳自动跳跃功能

    这篇文章主要介绍了使用Python实现跳一跳自动跳跃功能,本文图文并茂通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-07-07
  • PyTorch中的squeeze()和unsqueeze()解析与应用案例

    PyTorch中的squeeze()和unsqueeze()解析与应用案例

    这篇文章主要介绍了PyTorch中的squeeze()和unsqueeze()解析与应用案例,文章内容介绍详细,需要的小伙伴可以参考一下,希望对你有所帮助
    2022-03-03
  • python文字转语音的实例代码分析

    python文字转语音的实例代码分析

    在本篇文章里小编给大家整理的是关于python文字转语音的实例代码分析,有需要的朋友们可以参考下。
    2019-11-11
  • Python3实现取图片中特定的像素替换指定的颜色示例

    Python3实现取图片中特定的像素替换指定的颜色示例

    这篇文章主要介绍了Python3实现取图片中特定的像素替换指定的颜色,涉及Python3针对图片文件的读取、转换、生成等相关操作技巧,需要的朋友可以参考下
    2019-01-01
  • python中DataFrame常用的描述性统计分析方法详解

    python中DataFrame常用的描述性统计分析方法详解

    这篇文章主要介绍了python中DataFrame常用的描述性统计分析方法详解,描述性统计分析是通过图表或数学方法,对数据资料进行整理、分析,并对数据的分布状态、数字特征和随机变量之间的关系进行估计和描述的方法,需要的朋友可以参考下
    2023-07-07
  • Django中如何用xlwt生成表格的方法步骤

    Django中如何用xlwt生成表格的方法步骤

    这篇文章主要介绍了Django中如何用xlwt生成表格的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • python 解决selenium 中的 .clear()方法失效问题

    python 解决selenium 中的 .clear()方法失效问题

    这篇文章主要介绍了python 解决selenium 中的 .clear()方法失效问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Pygame的程序开始示例代码

    Pygame的程序开始示例代码

    这篇文章主要介绍了Pygame的程序开始的示例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05
  • python多进程实现数据共享的示例代码

    python多进程实现数据共享的示例代码

    本文介绍了Python中多进程实现数据共享的方法,包括使用multiprocessing模块和manager模块这两种方法,具有一定的参考价值,感兴趣的可以了解一下
    2025-01-01

最新评论