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_argcount,通过它们你可以以func的定义之外,还原func的参数列表,详见Python多重装饰器中的最后一个例子中的ArgsType;另外关键字参数是因为调用而出现的,而不是因为func的定义,func的定义中的用等号连接的只是有默认值的参数,它们并不一定会成为关键字参数,因为你仍然可以按照位置来传递它们。

Python各式装饰器的更多相关文章

  1. Python札记 -- 装饰器补充

    本随笔是对Python札记 -- 装饰器的一些补充. 使用装饰器的时候,被装饰函数的一些属性会丢失,比如如下代码: #!/usr/bin/env python def deco(func): def ...

  2. python基础——装饰器

    python基础——装饰器 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数. >>> def now(): ... print('2015-3-25 ...

  3. 【转】详解Python的装饰器

    原文链接:http://python.jobbole.com/86717/ Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现 ...

  4. 两个实用的Python的装饰器

    两个实用的Python的装饰器 超时函数 这个函数的作用在于可以给任意可能会hang住的函数添加超时功能,这个功能在编写外部API调用 .网络爬虫.数据库查询的时候特别有用 timeout装饰器的代码 ...

  5. python 基础——装饰器

    python 的装饰器,其实用到了以下几个语言特点: 1. 一切皆对象 2. 函数可以嵌套定义 3. 闭包,可以延长变量作用域 4. *args 和 **kwargs 可变参数 第1点,一切皆对象,包 ...

  6. 理解Python中的装饰器//这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档

    转自:http://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html 这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档 ...

  7. python基础—装饰器

    python基础-装饰器 定义:一个函数,可以接受一个函数作为参数,对该函数进行一些包装,不改变函数的本身. def foo(): return 123 a=foo(); b=foo; print(a ...

  8. 详解Python的装饰器

    Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现了say_hello()和say_goodbye()两个函数. def sa ...

  9. 关于python的装饰器(初解)

    在python中,装饰器(decorator)是一个主要的函数,在工作中,有了装饰器简直如虎添翼,许多公司面试题也会考装饰器,而装饰器的意思又很难让人理解. python中,装饰器是一个帮函数动态增加 ...

随机推荐

  1. 初识genymotion安装遇上的VirtualBox问题

    想必做过Android开发的都讨厌那慢如蜗牛的 eclipse原生Android模拟器吧! 光是启动这个模拟器都得花上两三分钟,慢慢的用起来手机来调试,但那毕竟不是长久之计,也确实不方便,后来知道了g ...

  2. 25 Killer Actions to Boost Your Self-Confidence

    25 Killer Actions to Boost Your Self-Confidence Once we believe in ourselves, we can risk curiosity, ...

  3. 搭建centos测试环境:window安装xshell,WinSCP 。 centos安装jdk tomcat

    通过ssh实现远程访问linux系统: 由于xshell 连接centos,需要centos开启ssh服务.所以先启动SSH服务,没有ssh需要先安装. 1 . 查看SSH是否安装命令:rpm -qa ...

  4. css样式表分类、选择器分类、css基础样式

    1 . 样式表  Cascading Style Sheet      css优势: 内容与表现分离 网页的表现统一,容易修改 丰富的样式,使网页布局更加灵活 减少网页代码量,增加网页的浏览速度,节省 ...

  5. JS开发HTML5游戏《神奇的六边形》(一)

    近期出现一款魔性的消除类HTML5游戏<神奇的六边形>,今天我们一起来看看如何通过开源免费的青瓷引擎(www.zuoyouxi.com)来实现这款游戏. (点击图片可进入游戏体验) 因内容 ...

  6. Oracle ITL(Interested Transaction List)理解

    ITL(Interested Transaction List) ITL是位于数据块头部的事物槽列表,它是由一系列的ITS(Interested Transaction Slot,事物槽)组成,其初始 ...

  7. MySQL模糊查询

    第一种最土的方法:使用like语句第二种用全文索引 有两种方法,第一种最土的方法:使用like语句第二种听涛哥说用全文索引,就在网上搜一下: 如何在MySQL中获得更好的全文搜索结果 mysql针对这 ...

  8. Java 中多条件排序

    Collections.sort(ghEntityList, new Comparator<GongHuiEntity>() { @Override public int compare( ...

  9. Android课程---关于下拉列表与状态栏提示的学习

    activity_ui7.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout x ...

  10. sweetalert api中文开发文档和手册

    官网和下载地址: http://t4t5.github.io/sweetalert/  2016年10月30日14:10:21 废话,目前php开发越来越API话,所以php方法很多都是json返回数 ...