Python入門之裝飾器九步學習入門

來源:互聯網
上載者:User

標籤:int   www.   lock   形參   ==   print   ros   def   module   

第一步:最簡單的函數,準備附加額外功能

‘‘‘樣本1: 最簡單的函數,表示調用了兩次‘‘‘ def myfunc():    print("myfunc() called.") myfunc()myfunc()

 

第二步:使用裝飾函數在函數執行前和執行後分別附加額外功能

‘‘‘樣本2: 替換函數(裝飾)裝飾函數的參數是被裝飾的函數對象,返回原函數對象裝飾的實質語句: myfunc = deco(myfunc)‘‘‘ def deco(func):    print("before myfunc() called.")    func()    print("  after myfunc() called.")    return func def myfunc():    print(" myfunc() called.") myfunc = deco(myfunc) myfunc()myfunc()

 

第三步:使用文法糖@來裝飾函數

‘‘‘樣本3: 使用文法糖@來裝飾函數,相當於“myfunc = deco(myfunc)”但發現新函數只在第一次被調用,且原函數多調用了一次‘‘‘ def deco(func):    print("before myfunc() called.")    func()    print("  after myfunc() called.")    return func @decodef myfunc():    print(" myfunc() called.") myfunc()myfunc()

 

第四步:使用內嵌封裝函數來確保每次新函數都被調用

‘‘‘樣本4: 使用內嵌封裝函數來確保每次新函數都被調用,內嵌封裝函數的形參和傳回值與原函數相同,裝飾函數返回內嵌封裝函數對象‘‘‘ def deco(func):    def _deco():        print("before myfunc() called.")        func()        print("  after myfunc() called.")        # 不需要返回func,實際上應返回原函數的傳回值    return _deco @decodef myfunc():    print(" myfunc() called.")    return ‘ok‘ myfunc()myfunc()

 

第五步:對帶參數的函數進行裝飾

‘‘‘樣本5: 對帶參數的函數進行裝飾,內嵌封裝函數的形參和傳回值與原函數相同,裝飾函數返回內嵌封裝函數對象‘‘‘ def deco(func):    def _deco(a, b):        print("before myfunc() called.")        ret = func(a, b)        print("  after myfunc() called. result: %s" % ret)        return ret    return _deco @decodef myfunc(a, b):    print(" myfunc(%s,%s) called." % (a, b))    return a + b myfunc(1, 2)myfunc(3, 4)

 

第六步:對參數數量不確定的函數進行裝飾

‘‘‘樣本6: 對參數數量不確定的函數進行裝飾,參數用(*args, **kwargs),自動適應變參和具名引數‘‘‘ def deco(func):    def _deco(*args, **kwargs):        print("before %s called." % func.__name__)        ret = func(*args, **kwargs)        print("  after %s called. result: %s" % (func.__name__, ret))        return ret    return _deco @decodef myfunc(a, b):    print(" myfunc(%s,%s) called." % (a, b))    return a+b @decodef myfunc2(a, b, c):    print(" myfunc2(%s,%s,%s) called." % (a, b, c))    return a+b+c myfunc(1, 2)myfunc(3, 4)myfunc2(1, 2, 3)myfunc2(3, 4, 5)

 

第七步:讓裝飾器帶參數

‘‘‘樣本7: 在樣本4的基礎上,讓裝飾器帶參數,和上一樣本相比在外層多了一層封裝。裝飾函數名實際上應更有意義些‘‘‘ def deco(arg):    def _deco(func):        def __deco():            print("before %s called [%s]." % (func.__name__, arg))            func()            print("  after %s called [%s]." % (func.__name__, arg))        return __deco    return _deco @deco("mymodule")def myfunc():    print(" myfunc() called.") @deco("module2")def myfunc2():    print(" myfunc2() called.") myfunc()myfunc2()

 

第八步:讓裝飾器帶 類 參數

‘‘‘樣本8: 裝飾器帶類參數‘‘‘ 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()myfunc()

 

第九步:裝飾器帶類參數,並分拆公用類到其他py檔案中,同時示範了對一個函數應用多個裝飾器

‘‘‘mylocker.py: 公用類 for 樣本9.py‘‘‘ 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

 

‘‘‘樣本9: 裝飾器帶類參數,並分拆公用類到其他py檔案中同時示範了對一個函數應用多個裝飾器‘‘‘ from mylocker import * 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))

 

 

參考

 

Python入門之裝飾器九步學習入門

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.