Python中的各种装饰器详解

 更新时间:2015年04月11日 10:40:34   投稿:junjie  
这篇文章主要介绍了Python中的各种装饰器详解,Python装饰器分两部分,一是装饰器本身的定义,一是被装饰器对象的定义,本文分别讲解了各种情况下的装饰器,需要的朋友可以参考下

Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义。

一、函数式装饰器:装饰器本身是一个函数。

1.装饰函数:被装饰对象是一个函数

[1]装饰器无参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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.被装饰对象有参数:

复制代码 代码如下:

>>> 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]装饰器有参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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)
>>>


由上面这段代码中的最后两个例子可知:当装饰器有参数时,即使你启用装饰器的默认参数,不另外传递新值进去,也必须有一对括号,否则编译器会直接将func传递给test(),而不是传递给_test()

b.被装饰对象有参数:

复制代码 代码如下:

>>> 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]装饰器无参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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.被装饰对象有参数:
复制代码 代码如下:

>>> 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]装饰器有参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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.被装饰对象有参数:
 

复制代码 代码如下:

 >>> 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__()来实现职能

1.装饰函数:被装饰对象是一个函数

[1]装饰器无参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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.被装饰对象有参数:

复制代码 代码如下:

>>> 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]装饰器有参数

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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'
>>>

或者:

复制代码 代码如下:

 >>> 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.被装饰对象有参数:
 

复制代码 代码如下:

 >>> 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'
>>>
 

 或者:
 

复制代码 代码如下:

 >>> 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]装饰器无参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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.被装饰对象有参数:
 

复制代码 代码如下:

 >>> 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]装饰器有参数:

a.被装饰对象无参数:

复制代码 代码如下:

>>> 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.被装饰对象有参数:
 

复制代码 代码如下:

 >>> 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'
>>>
 

 总结:【1】@decorator后面不带括号时(也即装饰器无参数时),效果就相当于先定义func或cls,而后执行赋值操作func=decorator(func)或cls=decorator(cls);

【2】@decorator后面带括号时(也即装饰器有参数时),效果就相当于先定义func或cls,而后执行赋值操作 func=decorator(decoratorArgs)(func)或cls=decorator(decoratorArgs)(cls);

【3】如上将func或cls重新赋值后,此时的func或cls也不再是原来定义时的func或cls,而是一个可执行体,你只需要传入参数就可调用,func(args)=>返回值或者输出,cls(args)=>object of cls;

【4】最后通过赋值返回的执行体是多样的,可以是闭包,也可以是外部函数;当被装饰的是一个类时,还可以是类内部方法,函数;

【5】另外要想真正了解装饰器,一定要了解func.func_code.co_varnames,func.func_defaults,通过它们你可以以func的定义之外,还原func的参数列表;另外关键字参数是因为调用而出现的,而不是因为func的定义,func的定义中的用等号连接的只是有默认值的参数,它们并不一定会成为关键字参数,因为你仍然可以按照位置来传递它们。

相关文章

  • Python中实现三目运算的方法

    Python中实现三目运算的方法

    这篇文章主要介绍了Python中实现三目运算的方法,本文用and/or 运算符模拟实现三目运算,需要的朋友可以参考下
    2015-06-06
  • Python利用递归实现文件的复制方法

    Python利用递归实现文件的复制方法

    今天小编就为大家分享一篇Python利用递归实现文件的复制方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Python函数中闭包和延迟绑定详情

    Python函数中闭包和延迟绑定详情

    这篇文章主要介绍了Python函数中闭包和延迟绑定详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • Python中的错误处理与调试技巧分享

    Python中的错误处理与调试技巧分享

    在软件开发过程中,错误是不可避免的,无论是在开发初期还是在项目后期,程序都可能会遇到各种各样的错误,本文将深入探讨 Python 中的错误处理机制、常见错误类型及其处理方法,并介绍一些实用的调试技巧,以提高开发效率和代码质量,需要的朋友可以参考下
    2025-01-01
  • python3中apply函数和lambda函数的使用详解

    python3中apply函数和lambda函数的使用详解

    本文主要介绍了python3中apply函数和lambda函数的使用详解,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • Python爬虫之获取心知天气API实时天气数据并弹窗提醒

    Python爬虫之获取心知天气API实时天气数据并弹窗提醒

    今天我们来学习如何获取心知天气API实时天气数据,制作弹窗提醒,并设置成自启动项目.文中有非常详细的代码示例及介绍,对正在学习python的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-05-05
  • windowns使用PySpark环境配置和基本操作

    windowns使用PySpark环境配置和基本操作

    pyspark是Spark对Python的api接口,可以在Python环境中通过调用pyspark模块来操作spark,这篇文章主要介绍了windowns使用PySpark环境配置和基本操作,感兴趣的可以了解一下
    2021-05-05
  • 使用Python脚本来获取Cisco设备信息的示例

    使用Python脚本来获取Cisco设备信息的示例

    这篇文章主要介绍了编写Python脚本来获取Python脚本来获取Cisco设备信息的教程,文中的示例是获取一台思科交换机的脚本,需要的朋友可以参考下
    2015-05-05
  • Flask web开发处理POST请求实现(登录案例)

    Flask web开发处理POST请求实现(登录案例)

    这篇文章主要介绍了Flask web开发处理POST请求实现(登录案例),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • Django框架模板语言实例小结【变量,标签,过滤器,继承,html转义】

    Django框架模板语言实例小结【变量,标签,过滤器,继承,html转义】

    这篇文章主要介绍了Django框架模板语言,结合实例形式总结分析了Django框架中变量,标签,过滤器,继承,html转义等相关模板语言操作技巧,需要的朋友可以参考下
    2019-05-05

最新评论