微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,5)
Call the function left().
'hello'
>>> @test(True)
def left(Str,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,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,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,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,5)
Call function
'hello'
>>>
 

 或者:
 


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

   
>>> @test()
def left(Str,Len):
    #The parameters of _call can be '(self,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,**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,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的定义中的用等号连接的只是有认值的参数,它们并不一定会成为关键字参数,因为你仍然可以按照位置来传递它们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登录的接口,其中 url 有一些非业务参数:ts、he、sign、secret。 然后根据这些参数作为关键词,定位到相关的 js 代码。 最后,逐步进行代码的跟踪,发现大部分的代码被混淆加密了。 花费了大半天,来还原这些混淆加密的代码
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登录 我们分析登录接口,发现调用了两次不同的接口;而且,需要先调用 https://login.huitun.com/weChat/userLogin,然后再调用 https://dyapi.huitun.com/userLogin 接口。 登
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接口,接入了阿里云的无痕验证码;通过接口方式模拟登录,难度比较高。所以,我们使用自动化的方式来实现模拟登录,并且获取到 cookie 数据。 [阿里无痕验证码] https://help.aliyun.com/document_detail/1
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密算法 通过接口进行模拟登录 我们先通过正常登录的方式,分析对应的登录接口。通过 F12 打开谷歌浏览器的调试面板,可以看到登录需要传递的一些参数;其中看到密码是被加密了。 不过我们通过经验可以大概猜测一下,应该是通过 md5 算法加密了。 接下
抽丝剥茧成功破解红人点集的签名加密算法 抽丝剥茧破解登录签名算法,成功实现模拟登录 headers = {} phone_num = &quot;xxxx&quot; password = &quot;xxxx&quot; md5_hash = hashlib.md5() md5_hash.upda
轻松绕过 Graphql 接口爬取有米有数的商品数据 有米有数数据的 API 接口,使用的是一种 API 查询语言 graphql。所有的 API 只有一个入口,具体的操作隐藏在请求数据体里面传输。 模拟登录,获取 sessionId 调用登录接口,进行模拟登录。 cookies = {} head
我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t