Python函数:装饰器
2015-09-30 11:21
881 查看
一、使用修饰函数在函数执行前和执行后分别附加额外功能
1.1 代码
1.2 运行结果
二、使用语法糖@来装饰函数
2.1 代码
2.2 运行结果
三、使用内建函数来确保每次新函数都会被调用
3.1 代码
3.2 运行结果
参考资料:
Python装饰器学习:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
1.1 代码
#!/usr/bin/env python def deco(func): print "before func called" func() print "after func called" return func def myfunc(): print "myfunc() called" myfunc = deco(myfunc) myfunc() myfunc()
1.2 运行结果
二、使用语法糖@来装饰函数
2.1 代码
#!/usr/bin/env python def deco(func): print "before func called" func() print "after func called" return func @deco def myfunc(): print "myfunc() called" myfunc() myfunc()
2.2 运行结果
三、使用内建函数来确保每次新函数都会被调用
3.1 代码
#!/usr/bin/env python def deco(func): def _deco(): print "before func called" func() print "after func called" return _deco @deco def myfunc(): print "myfunc() called" myfunc() myfunc()
3.2 运行结果
参考资料:
Python装饰器学习:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
相关文章推荐
- 初试VS2015提供的Python Django模版
- 2015/9/29 Python基础(20):类的授权
- python learn :字典
- 【Python】菜鸟学习笔记(3)数字
- Python中给文件加锁
- Python interface of LIBLINEAR
- Python 字典的创建赋值和动态扩展
- Python解析json文件报错:'utf8' codec can't decode byte 0xbb in position 0: invalid start byte
- Python 字典和列表的对比应用
- python的subprocess模块使用
- Python计算两个日期相差的天数
- LeetCode----Ugly NumberII
- python 初始化测试方法
- python运行类,能够执行
- python 操作文本编辑器
- Python时间函数
- python基础(1)
- 十分钟学会 Python
- python 实现文件复制,删除
- 《Python基础教程 (第2版 修订版)》 第2章 列表和元组(学习笔记· 一)