python装饰器class_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 "", 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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/349550.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

odoo controller 继承

方式一&#xff1a; 继承基类&#xff0c;直接重写方法 from odoo.addons.web.controllers.main import Exportclass PsExport(Export): http.route(/web/export/get_fields, typejson, auth"user") def get_fields(self, model, prefix, parent_name , import_co…

python字符串startswith_Python 字符串 startswith() 使用方法及示例

Python 字符串 startswith() 使用方法及示例如果字符串以指定的前缀(字符串)开头&#xff0c;则startswith()方法将返回True。如果不是&#xff0c;则返回False。startswith()的语法为&#xff1a;str.startswith(prefix[, start[, end]])startswith()参数startswith()方法最多…

odoo连接外部数据库

odoo框架默认的访问时Postgres数据库&#xff0c;但在实际的应用场景中&#xff0c;不可避免的使用到其他数据库&#xff0c;所以有必要研究如何连接其他第三方数据库&#xff0c;这里分享下OCA的相关模块&#xff0c;具体的源代码在这里。 我将第三方的数据库需要连接的情况汇…

整型和bcd的对应关系_微信与多闪之争背后,好友关系链到底是如何窃取的?

这几天从发布到全面推广&#xff0c;多闪已经快速的超越100万用户&#xff0c;迅速占领了appsotre榜首&#xff0c;在七麦数据中也是蝉联第一。但因多闪包括头条产品登录采取都支持【微信第三方登录】。很多用户都反馈是否自己的关系链被多闪、甚至是抖音窃取&#xff0c;并且腾…

线程同步,线程不同步_同步多线程集成测试

线程同步,线程不同步测试线程非常困难&#xff0c;这使得为被测多线程系统编写良好的集成测试非常困难。 这是因为在JUnit中&#xff0c;测试代码&#xff0c;被测对象和任何线程之间没有内置的同步。 这意味着&#xff0c;当您必须为创建并运行线程的方法编写测试时&#xff0…

ehcache 默认大小_简单的使用ehcache

ehcache是一个用Java实现的使用简单&#xff0c;高速&#xff0c;实现线程安全的缓存管理类库&#xff0c;ehcache提供了用内存&#xff0c;磁盘文件存储&#xff0c;以及分布式存储方式等多种灵活的cache管理方案。同时ehcache作为开放源代码项目&#xff0c;采用限制比较宽松…

JS定时器使用,定时定点,固定时刻,循环执行

本文概述&#xff1a;本文主要介绍通过JS实现定时定点执行&#xff0c;在某一个固定时刻执行某个函数的方法。比如说在下一个整点执行&#xff0c;在每一个整点执行&#xff0c;每隔10分钟定时执行的方法。 JavaScript中有两个定时器方法&#xff1a;setTimeout&#xff08;&am…

axios 跨域_当遇到跨域开发时,我们如何处理好前后端配置和请求库封装

我们知道很多大型项目都或多或少的采用跨域的模式开发, 以达到服务和资源的解耦和高效利用. 在大前端盛行的今天更为如此, 前端工程师可以通过nodejs或者Nginx轻松搭建起web服务器.这个时候我们只需要请求后端服务器的接口即可实现系统的业务功能开发.这个过程中会涉及到web页面…

Java数据类型和标识符

在本教程中&#xff0c;我们将了解Java中的数据类型和标识符。 Java语言具有丰富的数据类型实现。 数据类型指定大小和可以存储在标识符中的值的类型。 Java数据类型分为两类&#xff1a; 原始数据类型 非原始数据类型 原始类型 Java定义了八种原始数据类型&#xff1a;字…

哈罗顺风车送到终点吗_没有了顺风车,滴滴“特惠拼车”来了!比拼车更低价,比顺风车更安全吗?...

近日&#xff0c;有网友表示&#xff0c;滴滴出行App内出现了“特惠拼车”功能&#xff0c;据悉&#xff0c;该功能主要给乘客提供长距离拼车出行的优惠折扣。如果拼车价格为44.8元&#xff0c;那“特惠拼车”的价格为30.7元。但是该功能目前还未在上海出现。近日&#xff0c;有…

管理角色认知-工程师到管理者角色发生了哪些变化?

背景 不同等级的管理者需求不同&#xff1b; 管理者需求说明新经理提供管理相关的工具和方法能力层面&#xff0c;术高级经理提升角色认知认知和理解&#xff0c;道&#xff0c;系统通过认知上的改变达到能力和行为上的改善一个人的行为&#xff0c;能力&#xff0c;价值观都源…

axure 小程序 lib_小程序定制开发的步骤有哪些?

经过两年多的微信小程序开发&#xff0c;各种功能应用变得越来越成熟&#xff0c;越来越多的企业和企业正在开发微信小程序用于在线营销。如果您的公司尚未开发成都小程序&#xff0c;它将变得越来越凶猛。在竞争激烈的市场环境中&#xff0c;将失去许多获得和营销客户的机会。…

java 检查打印机状态_爱普生打印机常见故障有哪些 爱普生打印机故障解决方法【详解】...

任何设备在使用一段时间后都会出现一些小问题&#xff0c;打印机也不例外&#xff0c;那么爱普生打印机常见的故障有哪些 &#xff0c;出现问题该怎么解决呢&#xff1f;下面小编就来分享2018爱普生打印机故障解决方法 &#xff0c;一起来看看吧&#xff01;一、故障现象 &a…

eureka 之前的服务如何关闭_干货分享 | 服务注册中心Spring Cloud Eureka部分源码分析...

友情提示&#xff1a;全文13000多文字&#xff0c;预计阅读时间10-15分钟Spring Cloud Eureka作为常用的服务注册中心&#xff0c;我们有必要去了解其内在实现机制&#xff0c;这样出现问题的时候我们可以快速去定位问题。当我们搭建好Eureka Server服务注册中心并启动后&#…

局部变量写在循环内还是外_循环内的局部变量和性能

局部变量写在循环内还是外总览 有时会出现一个问题&#xff0c;即分配一个新的局部变量需要多少工作。 我的感觉一直是&#xff0c;代码已优化到成本为静态的程度&#xff0c;即一次执行&#xff0c;而不是每次运行都执行一次。 最近&#xff0c; Ishwor Gurung建议考虑将一些…

csp-s模拟测试44「D·E·F」

用心出题,用脚造数据 乱搞场 1 #include<bits/stdc.h>2 #define re register3 #define int long long4 #define inf 0x7ffffffffffffff5 using namespace std;6 int n,a[100010],b[100010],ansinf;7 double st,ed;8 inline int read(){9 re int a0,b1; re char chget…

c++中的new_怎么在java中创建一个自定义的collector

简介在之前的java collectors文章里面&#xff0c;我们讲到了stream的collect方法可以调用Collectors里面的toList()或者toMap()方法&#xff0c;将结果转换为特定的集合类。今天我们介绍一下怎么自定义一个Collector。Collector介绍我们先看一下Collector的定义&#xff1a;Co…

Java 9中的新Regex功能

最近&#xff0c;我收到了Packt出版的Anubhava Srivastava提供的免费书籍“ Java 9 Regular Expressions” 。 这本书是一个很好的教程&#xff0c;它向任何想学习正则表达式并从头开始的人介绍。 那些知道如何使用正则表达式的人可能仍然很有趣&#xff0c;以重申其知识并加深…

c语言实现二分法_C语言实现二分法求解方程在区间内的根

C语言实现二分法求解方程在区间内的根。设有非线性方程&#xff1a;其中&#xff0c; 为 上连续函数且设 (不妨设方程在 内仅有一个实根)&#xff0c;求上述方程实根的二分法过程&#xff0c;就是将含根区间[a,b]逐步分半&#xff0c;检查函数值符号的变化&#xff0c;以便确定…

计划

赤 wqs二分 https://www.cnblogs.com/Juve/p/11479423.html https://www.cnblogs.com/Rorschach-XR/p/11479602.html 反悔贪心 https://www.cnblogs.com/cjyyb/p/9367948.html https://www.cnblogs.com/Miracevin/p/9795871.html https://blog.csdn.net/weixin_34344677/articl…