• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python中的各种装饰器详解

python 搞代码 4年前 (2022-01-09) 32次浏览 已收录 0个评论

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

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

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

[1]装饰器无参数:

a.被装饰对象无参数:

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

>>> @test
def say():return ‘hello world’

>>> say()
Call the function say().
‘hello world’
>>>

b.被装饰对象有参数:

<br />>>> def test(func):<br />    def _test(*args,**kw):<br />        print 'Call the function %s().'%func.func_name<br />        return func(*args,**kw)<br />    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.被装饰对象无参数:

<br />>>> def test(printResult=False):<br />    def _test(func):<br />        def __test():<br />            print 'Call the function %s().'%func.func_name<br />            if printResult:<br />                print func()<br />            else:<br />                return func()<br />        return __test<br />    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 “”, line 1, in
say()
TypeError: _test() takes exactly 1 argument (0 given)
>>>

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

b.被装饰对象有参数:

<br />>>> def test(printResult=False):<br />    def _test(func):<br />        def __test(*args,**kw):<br />            print 'Call the function %s().'%func.func_name<br />            if printResult:<br />                print func(*args,**kw)<br />            else:<br />                return func(*args,**kw)<br />        return __test<br />    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.被装饰对象无参数:

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

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

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

>>> s.value
32
>>>

b.被装饰对象有参数:

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

>>> s.value
‘hello world’
>>>

[2]装饰器有参数:

a.被装饰对象无参数:

<br />>>> def test(printValue=True):<br />    def _test(cls):<br />        def __test():<br />            clsName=re.findall('(\w+)',repr(cls))[-1]<br />            print 'Call %s.__init().'%clsName<br />            obj=cls()<br />            if printValue:<br />                print 'value = %r'%obj.value<br />            return obj<br />        return __test<br />    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.被装饰对象有参数:

<br /> >>> def test(printValue=True):<br />    def _test(cls):<br />        def __test(*args,**kw):<br />            clsName=re.findall('(\w+)',repr(cls))[-1]<br />            print 'Call %s.__init().'%clsName<br />            obj=cls(*args,**kw)<br />            if printValue:<br />                print 'value = %r'%obj.value<br />            return obj<br />        return __test<br />    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.被装饰对象无参数:

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

>>> @test
def say():
return ‘hello world’

>>> say()
‘hello world’
>>>

b.被装饰对象有参数:

<br />>>> class test(object):<br />    def __init__(self,func):<br />        self._func=func<br />    def __call__(self,*args,**kw):<br />        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.被装饰对象无参数:

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

>>> @test()
def say():
return ‘hello world’

>>> say()
Call function
‘hello world’
>>>

或者:

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

>>> @test()
def say():
return ‘hello world’

>>> say()
Call function
‘hello world’
>>>

b.被装饰对象有参数:

<br /> >>> class test(object):<br />    def __init__(self,beforeinfo='Call function'):<br />        self.beforeInfo=beforeinfo<br />    def __call__(self,func):<br />        def _call(*args,**kw):<br />            print self.beforeInfo<br />            return func(*args,**kw)<br />        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’
>>>

或者:

<br /> >>> class test(object):<br />    def __init__(self,beforeinfo='Call function'):<br />        self.beforeInfo=beforeinfo<br />    def __call__(self,func):<br />        self._func=func<br />        return self._call<br />    def _call(self,*args,**kw):<br />        print self.beforeInfo<br />        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.被装饰对象无参数:

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

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

>>> s=sy()
>>> s

>>> s.value
32
>>>

b.被装饰对象有参数:

<br /> >>> class test(object):<br />    def __init__(self,cls):<br />        self._cls=cls<br />    def __call__(self,*args,**kw):<br />        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

>>> s.value
‘hello world’
>>>

[2]装饰器有参数:

a.被装饰对象无参数:

<br />>>> class test(object):<br />    def __init__(self,printValue=False):<br />        self._printValue=printValue<br />    def __call__(self,cls):<br />        def _call():<br /><b>本文来源gao@!dai!ma.com搞$$代^@码!网</b>            obj=cls()<br />            if self._printValue:<br />                print 'value = %r'%obj.value<br />            return obj<br />        return _call

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

>>> s=sy()
value = 32
>>> s

>>> s.value
32
>>>

b.被装饰对象有参数:

<br /> >>> class test(object):<br />    def __init__(self,printValue=False):<br />        self._printValue=printValue<br />    def __call__(self,cls):<br />        def _call(*args,**kw):<br />            obj=cls(*args,**kw)<br />            if self._printValue:<br />                print 'value = %r'%obj.value<br />            return obj<br />        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

>>> 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的定义中的用等号连接的只是有默认值的参数,它们并不一定会成为关键字参数,因为你仍然可以按照位置来传递它们。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python中的各种装饰器详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址