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 '', line 1, in 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

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

>>> 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.装饰函数:被装饰对象是一个函数

三级分销系统

抽脂价目表

客户管理系统

ui培训

尿路感染的症状

集成墙面什么牌子好

女孩发育

视频播放

[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

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

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

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

>>> 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中的各种装饰器详解相关推荐

  1. python常用的装饰器库_Python中的各种装饰器详解

    Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...

  2. python编程字典100例_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  3. python编程midi键盘按键_Python中捕获键盘的方式详解

    python中捕获键盘操作一共有两种方法 第一种方法: 使用pygame中event方法 使用方式如下:使用键盘右键为例 if event.type = pygame.KEYDOWN and even ...

  4. python find的使用方法_Python中的rfind()方法使用详解

    Python中的rfind()方法使用详解 rfind()方法返回所在子str 被找到的最后一个索引,或者-1,如果没有这样的索引不存在,可选择限制搜索字符串string[beg:end]. 语法 以 ...

  5. python两个装饰器执行顺序_python中多个装饰器的执行顺序详解

    装饰器是程序开发中经常会用到的一个功能,也是python语言开发的基础知识,如果能够在程序中合理的使用装饰器,不仅可以提高开发效率,而且可以让写的代码看上去显的高大上^_^ 使用场景 可以用到装饰器的 ...

  6. python装饰器的顺序_python中多个装饰器的执行顺序详解

    装饰器是程序开发中经常会用到的一个功能,也是python语言开发的基础知识,如果能够在程序中合理的使用装饰器,不仅可以提高开发效率,而且可以让写的代码看上去显的高大上^_^ 使用场景 可以用到装饰器的 ...

  7. python装饰器class_Python中的各种装饰器详解

    Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...

  8. python两个装饰器执行顺序_python中多个装饰器的执行顺序

    今天讲一下python中装饰器的执行顺序,以两个装饰器为例. 装饰器代码如下: def wrapper_out1(func): print('--out11--') def inner1(*args, ...

  9. 在python中、对于函数定义代码的理解_python中如何理解装饰器代码?

    长文预警,[最浅显易懂的装饰器讲解] 能不能专业地复制题目?配上代码,问题分段. 我来给提主配上问题的代码. 正式回答: 1:如何理解return一个函数,它与return一个值得用法区别在哪? 敲黑 ...

最新文章

  1. 深度学习在不同领域的应用,我去,这也行!?
  2. 艾伟:正则表达式30分钟入门教程
  3. 公众号点击图片变成另一张_微信公众号点击出现图片是怎么实现的?
  4. Python3空字符串和len()函数
  5. 检索数据_6_过滤记录结合使用别名
  6. PHP 如何实现多进程 and mysql查询效率
  7. 数组遍历VS对象遍历
  8. 腾讯优图发布四大平台产品,持续开放视觉AI能力
  9. vantUI弹框组件 message文字,如何换行 ?
  10. 远程linux服务器,安装集成的xampp,本地电脑远程连接数据库进行使用
  11. 华为云AI斩获2019数博会“黑科技”等四大奖项
  12. 我的桌面秀(ubuntu3d)
  13. 模电课程设计_函数发生器
  14. 群晖Docker的高级操作
  15. CAD2016 画直线时第二点为相对坐标(相对第一个点的坐标),非绝对坐标
  16. AR红包Android端实现原理
  17. VMware教程:设置 CentOS 7 共享文件夹
  18. MySQL数据库基础--数据管理
  19. mousedown mouseup click 触发顺序
  20. Mac M1 安装Maven

热门文章

  1. 1.1 typescript中的interface
  2. Kali Linux 无线渗透测试入门指南 第七章 高级 WLAN 攻击
  3. 六年级计算机考试实验操作,小学科学实验操作考试试题(六年级)
  4. opencv项目1----自动识别车牌并手动保存车牌信息
  5. 9适应之力加多少攻击_英雄联盟加9适应之力
  6. UE4风格化水体制作
  7. 喜讯频传 英特尔为电竞产业持续赋能
  8. 投影仪的裸眼3D效果
  9. Untitled (1)
  10. 输入起始时间,第几周,周几,自动计算出日期