python 装饰器
来源:互联网 发布:蓝牙单片机 编辑:程序博客网 时间:2024/06/11 02:54
装饰器:由于函数是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数:def now(): print '2013-120-25'now()f=nowprint ff()C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a6.py2013-120-25<function now at 0x0253FA70>2013-120-25现在,假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。本质上,decorator 就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,可以定义如下:def wrapper(*args): print '------------' print args print type(args) print '------------'wrapper(1,2,3,4)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a6.py------------(1, 2, 3, 4)<type 'tuple'>------------Process finished with exit code 0此时传入的是个元组def wrapper(**kw): print '------------' print kw print type(kw) print '------------'wrapper(size='large', quantity=6,sex='man')C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a6.py------------{'quantity': 6, 'sex': 'man', 'size': 'large'}<type 'dict'>------------def log(func): def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw) return wrapper@logdef now(): print '2013-12-25'now()C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a17.pycall now():2013-12-25
阅读全文
0 0
- python装饰器装饰类
- [python]python装饰器
- Python装饰器学习
- Python装饰器
- python 装饰器
- Python装饰器
- python 装饰器 应用
- python 装饰器2
- Python装饰器学习
- python装饰器
- python装饰器
- python 装饰器入门
- python装饰器
- python装饰器
- python 装饰器'@'
- python装饰器
- Python装饰器详解
- python 装饰器
- Android中使用封装的OKHttp上传图片,从相机和相册中获取图片并剪切
- 自然语言处理 之 语料库相关(三)
- 如何辨认一个复杂声明表达式子中变量的类型?
- sorted排序
- iOS 按钮防止被重复点击
- python 装饰器
- 重做OpenVPN服务器
- 敲诈完微软,又让苹果赔29亿,有文化的流氓真可怕
- Android沉浸式之一步到位(fragment 的坑之解法)
- Android 端天气预报APP的实现(四)使用ViewPager展示天气数据
- board-mx6q_sabresd.c源码阅读笔记
- BZOJ1602 [Usaco2008 Oct]牧场行走
- Spring Batch 学习
- leetcode 198|213. House Robber 1|2