装饰器
2016-03-09 15:24
375 查看
#定义函数: def hello(*args,**kw): print 'ab' print args print kw args=range(1,5) hello(args) #返回值: ab ([1, 2, 3, 4],) {} #定义装饰函数: def dec(fun): def wrapper(*args,**kw): print 'do sth. before' fun(*args,**kw) print 'do sth. after' return wrapper dec(hello(args)) #将hello函数及参数当做变量赋予dec,只相当于直接执行hello(args),返回值: ab ([1, 2, 3, 4],) {} p=dec(hello) p(args) dec(hello)(args) #将函数当做变量赋予dec,然后通过变量调用函数,再赋予变量变量,返回值: do sth. before ab ([1, 2, 3, 4],) {} do sth. after
def dec(fun): def wrapper(*args,**kw): print 'do sth. before' fun(*args,**kw) #此处如果改为 return fun(*args,**kw),则下一句print 'after'不会再执行。在函数中,遇到第一个return则不会再执行后面的语句,如果返回两个值,可以写在同一行。如果用了return,函数执行完会得到结果,没有return则无返回值 print 'do sth. after' return wrapper @dec #通过@调用装饰函数 def hello(*args,**kw): print 'ab' print args print kw args=range(1,5) hello(args)
相关文章推荐
- 时间片轮转代码中的汇编代码分析
- java数字前补0
- List, Set, Map是否继承自Collection接口?
- linux7的网卡命名机制,名称组成格式;
- cmake使用等(转)
- mapi pst
- Linux下简单线程池的实现
- Tomcat 安全配置与性能优化
- 【转】iOS 开发怎么入门?
- 自我介绍
- [LeetCode]题解(python):109-Convert Sorted List to Binary Search Tree
- 浅谈命令查询职责分离(CQRS)模式---转载
- c++与web交互socket该发送的协议数据
- Performing stop of activity that is not resumed #12
- php手动释放内存
- 深入理解HTTP协议
- 高性能网站架构之缓存篇—Redis集群搭建
- Java编程练习之判断Java文件名是否正确,判断邮箱格式是否正确和统计指定字符串中某字符现的次数
- Ubuntu 14.04安装搜狗拼音linux版应该注意的问题
- 几个常用的git命令