欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中的各種裝飾器詳解

 更新時間:2015年04月11日 10:40:34   投稿:junjie  
這篇文章主要介紹了Python中的各種裝飾器詳解,Python裝飾器分兩部分,一是裝飾器本身的定義,一是被裝飾器對象的定義,本文分別講解了各種情況下的裝飾器,需要的朋友可以參考下

Python裝飾器,分兩部分,一是裝飾器本身的定義,一是被裝飾器對象的定義。

一、函數(shù)式裝飾器:裝飾器本身是一個函數(shù)。

1.裝飾函數(shù):被裝飾對象是一個函數(shù)

[1]裝飾器無參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> def test(func):
    def _test():
        print 'Call the function %s().'%func.func_name
        return func()
    return _test

>>> @test
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>>

b.被裝飾對象有參數(shù):

復(fù)制代碼 代碼如下:

>>> def test(func):
    def _test(*args,**kw):
        print 'Call the function %s().'%func.func_name
        return func(*args,**kw)
    return _test

>>> @test
def left(Str,Len):
    #The parameters of _test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
'hello'
>>>

[2]裝飾器有參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> def test(printResult=False):
    def _test(func):
        def __test():
            print 'Call the function %s().'%func.func_name
            if printResult:
                print func()
            else:
                return func()
        return __test
    return _test

>>> @test(True)
def say():return 'hello world'

>>> say()
Call the function say().
hello world
>>> @test(False)
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>> @test()
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>> @test
def say():return 'hello world'

>>> say()

Traceback (most recent call last):
  File "<pyshell#224>", line 1, in <module>
    say()
TypeError: _test() takes exactly 1 argument (0 given)
>>>


由上面這段代碼中的最后兩個例子可知:當(dāng)裝飾器有參數(shù)時,即使你啟用裝飾器的默認參數(shù),不另外傳遞新值進去,也必須有一對括號,否則編譯器會直接將func傳遞給test(),而不是傳遞給_test()

b.被裝飾對象有參數(shù):

復(fù)制代碼 代碼如下:

>>> def test(printResult=False):
    def _test(func):
        def __test(*args,**kw):
            print 'Call the function %s().'%func.func_name
            if printResult:
                print func(*args,**kw)
            else:
                return func(*args,**kw)
        return __test
    return _test

>>> @test()
def left(Str,Len):
    #The parameters of __test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
'hello'
>>> @test(True)
def left(Str,Len):
    #The parameters of __test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
hello
>>>


 
2.裝飾類:被裝飾的對象是一個類

[1]裝飾器無參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> def test(cls):
    def _test():
        clsName=re.findall('(\w+)',repr(cls))[-1]
        print 'Call %s.__init().'%clsName
        return cls()
    return _test

>>> @test
class sy(object):
    value=32

   
>>> s=sy()
Call sy.__init().
>>> s
<__main__.sy object at 0x0000000002C3E390>
>>> s.value
32
>>>


b.被裝飾對象有參數(shù):
復(fù)制代碼 代碼如下:

>>> def test(cls):
    def _test(*args,**kw):
        clsName=re.findall('(\w+)',repr(cls))[-1]
        print 'Call %s.__init().'%clsName
        return cls(*args,**kw)
    return _test

>>> @test
class sy(object):
    def __init__(self,value):
                #The parameters of _test can be '(value)' in this case.
        self.value=value

       
>>> s=sy('hello world')
Call sy.__init().
>>> s
<__main__.sy object at 0x0000000003AF7748>
>>> s.value
'hello world'
>>>


 [2]裝飾器有參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> def test(printValue=True):
    def _test(cls):
        def __test():
            clsName=re.findall('(\w+)',repr(cls))[-1]
            print 'Call %s.__init().'%clsName
            obj=cls()
            if printValue:
                print 'value = %r'%obj.value
            return obj
        return __test
    return _test

>>> @test()
class sy(object):
    def __init__(self):
        self.value=32

       
>>> s=sy()
Call sy.__init().
value = 32
>>> @test(False)
class sy(object):
    def __init__(self):
        self.value=32

       
>>> s=sy()
Call sy.__init().
>>>

 b.被裝飾對象有參數(shù):
 

復(fù)制代碼 代碼如下:

 >>> def test(printValue=True):
    def _test(cls):
        def __test(*args,**kw):
            clsName=re.findall('(\w+)',repr(cls))[-1]
            print 'Call %s.__init().'%clsName
            obj=cls(*args,**kw)
            if printValue:
                print 'value = %r'%obj.value
            return obj
        return __test
    return _test

>>> @test()
class sy(object):
    def __init__(self,value):
        self.value=value

       
>>> s=sy('hello world')
Call sy.__init().
value = 'hello world'
>>> @test(False)
class sy(object):
    def __init__(self,value):
        self.value=value

       
>>> s=sy('hello world')
Call sy.__init().
>>>
 


 二、類式裝飾器:裝飾器本身是一個類,借用__init__()和__call__()來實現(xiàn)職能

1.裝飾函數(shù):被裝飾對象是一個函數(shù)

[1]裝飾器無參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> class test(object):
    def __init__(self,func):
        self._func=func
    def __call__(self):
        return self._func()

   
>>> @test
def say():
    return 'hello world'

>>> say()
'hello world'
>>>

b.被裝飾對象有參數(shù):

復(fù)制代碼 代碼如下:

>>> class test(object):
    def __init__(self,func):
        self._func=func
    def __call__(self,*args,**kw):
        return self._func(*args,**kw)

   
>>> @test
def left(Str,Len):
    #The parameters of __call__ can be '(self,Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
'hello'
>>>

 [2]裝飾器有參數(shù)

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        def _call():
            print self.beforeInfo
            return func()
        return _call

   
>>> @test()
def say():
    return 'hello world'

>>> say()
Call function
'hello world'
>>>

或者:

復(fù)制代碼 代碼如下:

 >>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        self._func=func
        return self._call
    def _call(self):
        print self.beforeInfo
        return self._func()

   
>>> @test()
def say():
    return 'hello world'

>>> say()
Call function
'hello world'
>>>

 b.被裝飾對象有參數(shù):
 

復(fù)制代碼 代碼如下:

 >>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        def _call(*args,**kw):
            print self.beforeInfo
            return func(*args,**kw)
        return _call

   
>>> @test()
def left(Str,Len):
    #The parameters of _call can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call function
'hello'
>>>
 

 或者:
 

復(fù)制代碼 代碼如下:

 >>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        self._func=func
        return self._call
    def _call(self,*args,**kw):
        print self.beforeInfo
        return self._func(*args,**kw)

   
>>> @test()
def left(Str,Len):
    #The parameters of _call can be '(self,Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call function
'hello'
>>>
 


  2.裝飾類:被裝飾對象是一個類

[1]裝飾器無參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> class test(object):
    def __init__(self,cls):
        self._cls=cls
    def __call__(self):
        return self._cls()

   
>>> @test
class sy(object):
    def __init__(self):
        self.value=32

   
>>> s=sy()
>>> s
<__main__.sy object at 0x0000000003AAFA20>
>>> s.value
32
>>>

 b.被裝飾對象有參數(shù):
 

復(fù)制代碼 代碼如下:

 >>> class test(object):
    def __init__(self,cls):
        self._cls=cls
    def __call__(self,*args,**kw):
        return self._cls(*args,**kw)

   
>>> @test
class sy(object):
    def __init__(self,value):
        #The parameters of __call__ can be '(self,value)' in this case.
        self.value=value

       
>>> s=sy('hello world')
>>> s
<__main__.sy object at 0x0000000003AAFA20>
>>> s.value
'hello world'
>>>
 

 [2]裝飾器有參數(shù):

a.被裝飾對象無參數(shù):

復(fù)制代碼 代碼如下:

>>> class test(object):
    def __init__(self,printValue=False):
        self._printValue=printValue
    def __call__(self,cls):
        def _call():
            obj=cls()
            if self._printValue:
                print 'value = %r'%obj.value
            return obj
        return _call

   
>>> @test(True)
class sy(object):
    def __init__(self):
        self.value=32

       
>>> s=sy()
value = 32
>>> s
<__main__.sy object at 0x0000000003AB50B8>
>>> s.value
32
>>>

 b.被裝飾對象有參數(shù):
 

復(fù)制代碼 代碼如下:

 >>> class test(object):
    def __init__(self,printValue=False):
        self._printValue=printValue
    def __call__(self,cls):
        def _call(*args,**kw):
            obj=cls(*args,**kw)
            if self._printValue:
                print 'value = %r'%obj.value
            return obj
        return _call

   
>>> @test(True)
class sy(object):
    def __init__(self,value):
        #The parameters of _call can be '(value)' in this case.
        self.value=value

       
>>> s=sy('hello world')
value = 'hello world'
>>> s
<__main__.sy object at 0x0000000003AB5588>
>>> s.value
'hello world'
>>>
 

 總結(jié):【1】@decorator后面不帶括號時(也即裝飾器無參數(shù)時),效果就相當(dāng)于先定義func或cls,而后執(zhí)行賦值操作func=decorator(func)或cls=decorator(cls);

【2】@decorator后面帶括號時(也即裝飾器有參數(shù)時),效果就相當(dāng)于先定義func或cls,而后執(zhí)行賦值操作 func=decorator(decoratorArgs)(func)或cls=decorator(decoratorArgs)(cls);

【3】如上將func或cls重新賦值后,此時的func或cls也不再是原來定義時的func或cls,而是一個可執(zhí)行體,你只需要傳入?yún)?shù)就可調(diào)用,func(args)=>返回值或者輸出,cls(args)=>object of cls;

【4】最后通過賦值返回的執(zhí)行體是多樣的,可以是閉包,也可以是外部函數(shù);當(dāng)被裝飾的是一個類時,還可以是類內(nèi)部方法,函數(shù);

【5】另外要想真正了解裝飾器,一定要了解func.func_code.co_varnames,func.func_defaults,通過它們你可以以func的定義之外,還原func的參數(shù)列表;另外關(guān)鍵字參數(shù)是因為調(diào)用而出現(xiàn)的,而不是因為func的定義,func的定義中的用等號連接的只是有默認值的參數(shù),它們并不一定會成為關(guān)鍵字參數(shù),因為你仍然可以按照位置來傳遞它們。

相關(guān)文章

  • 零基礎(chǔ)寫python爬蟲之抓取百度貼吧代碼分享

    零基礎(chǔ)寫python爬蟲之抓取百度貼吧代碼分享

    前面幾篇都是以介紹基礎(chǔ)知識為主,各位童鞋估計都在犯嘀咕了,你到底寫不寫爬蟲????額,好吧,本文就給大家寫一個簡單的百度貼吧的python爬蟲代碼。
    2014-11-11
  • Python實現(xiàn)加密的RAR文件解壓的方法(密碼已知)

    Python實現(xiàn)加密的RAR文件解壓的方法(密碼已知)

    這篇文章主要介紹了Python實現(xiàn)加密的RAR文件解壓,本文分步驟給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • Python常用數(shù)據(jù)類型之列表使用詳解

    Python常用數(shù)據(jù)類型之列表使用詳解

    列表是Python中的基礎(chǔ)數(shù)據(jù)類型之一,其他語言中也有類似于列表的數(shù)據(jù)類型,比如js中叫數(shù)組,他是以[ ]括起來,每個元素以逗號隔開,而且他里面可以存放各種數(shù)據(jù)類型。本文將通過示例詳細講解列表的使用,需要的可以參考一下
    2022-04-04
  • 簡單掌握Python的Collections模塊中counter結(jié)構(gòu)的用法

    簡單掌握Python的Collections模塊中counter結(jié)構(gòu)的用法

    counter數(shù)據(jù)結(jié)構(gòu)被用來提供技術(shù)功能,形式類似于Python中內(nèi)置的字典結(jié)構(gòu),這里通過幾個小例子來簡單掌握Python的Collections模塊中counter結(jié)構(gòu)的用法:
    2016-07-07
  • python實現(xiàn)字符串完美拆分split()的方法

    python實現(xiàn)字符串完美拆分split()的方法

    今天小編就為大家分享一篇python實現(xiàn)字符串完美拆分split()的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python編寫函數(shù)注意事項總結(jié)

    python編寫函數(shù)注意事項總結(jié)

    在本篇文章里小編給大家分享了一篇關(guān)于python編寫函數(shù)注意事項總結(jié)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2021-03-03
  • python 列表元素左右循環(huán)移動 的多種解決方案

    python 列表元素左右循環(huán)移動 的多種解決方案

    這篇文章主要介紹了python 列表元素左右循環(huán)移動 的多種解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • Python 比較兩個 CSV 文件的三種方法并打印出差異

    Python 比較兩個 CSV 文件的三種方法并打印出差異

    這篇文章主要介紹了Python 比較兩個 CSV 文件并打印出差異,本文將討論比較兩個 CSV 文件的各種方法,我們將包括執(zhí)行此操作的最“Pythonic”方式和可幫助簡化此任務(wù)的外部 Python 模塊,需要的朋友可以參考下
    2023-06-06
  • Python 獲得13位unix時間戳的方法

    Python 獲得13位unix時間戳的方法

    本篇文章主要介紹了Python 獲得13位unix時間戳的方法,非常具有實用價值,需要的朋友可以參考下
    2017-10-10
  • python操作xlsx格式文件并讀取

    python操作xlsx格式文件并讀取

    python操作xlsx格式文件是比較常見的一個問題,本文給大家介紹xlrd庫讀取,pandas庫讀取的實例代碼,給大家講解的很詳細,需要的朋友跟隨小編一起看看吧
    2021-06-06

最新評論