程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 更多關於編程 >> python函數裝飾器用法實例詳解

python函數裝飾器用法實例詳解

編輯:更多關於編程

       本文實例講述了python函數裝飾器用法。分享給大家供大家參考。具體如下:

      裝飾器經常被用於有切面需求的場景,較為經典的有插入日志、性能測試、事務處理等。裝飾器是解決這類問題的絕佳設計,

      有了裝飾器,我們就可以抽離出大量函數中與函數功能本身無關的雷同代碼並繼續重用。概括的講,裝飾器的作用就是為已經存在的對象添加額外的功能。

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #! 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()

      輸出:

      ?

    1 2 3 test start in foo end start

      裝飾器修飾帶參數的函數:

      ?

    1 2 3 4 5 6 7 8 9 10 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')

      輸出:

      ?

    1 2 3 4 >>> test start parameter_foo:hello end start

      裝飾器修飾不確定參數個數的函數:

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 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)

      輸出:

      ?

    1 2 3 4 5 6 test start a end start test start 1 2 3 4 end start

      帶參數的裝飾器,再包一層就可以了:

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 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....')

      輸出:

      ?

    1 2 3 4 5 in much_test test start one at:10 python.... end start

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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()

      輸出:

      ?

    1 2 3 4 5 6 >>> before myfunc called [__main__.locker]. locker.acquire() called.(這是靜態方法) myfunc() called. locker.release() called.(不需要對象實例 >>>

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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))

      輸出:

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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程序設計有所幫助。

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved