python学习系列之python装饰器基础(2)---装饰含返回值的函数
2015-11-29 23:57
771 查看
在上篇基础(1)中,我写了一个装饰器及使用方法,但是如果遇到一个函数带返回值的话,就不好使了,因此重写一个装饰器如下:
本文出自 “苦咖啡's运维之路” 博客,请务必保留此出处http://alsww.blog.51cto.com/2001924/1718015
#basic2.py #coding:utf-8 def auth(func): def inner(*arg, **kwargs): print 'before' temp = func(*arg,**kwargs) #这行是关键,func相当于fetch_server_list print 'after' return temp #相当于返回fetch_server_list的值,又由于原函数fetch_server_list的值相当于返回 server_list的值,所以最终能得到 ['a1','a2','a3']。 return inner @auth def fetch_server_list(arg): serve_list = ['a1','a2','a3'] return serve_list调用这个装饰器:
#b2.py import basic2 ret_list = basic2.fetch_server_list('test') print ret_list执行结果:
#python b2.py before after ['a1', 'a2', 'a3']
本文出自 “苦咖啡's运维之路” 博客,请务必保留此出处http://alsww.blog.51cto.com/2001924/1718015
相关文章推荐
- 写给Python程序员的Scala入门教程
- Python第三方库安装技巧
- python django 数据库查询
- python协程
- python 的类变量和对象变量
- 逐行快速读入
- Python 代码风格 和 PEP8
- 【Python系列5】set和list的妙用
- python 3 输入和输出
- leetcode implement strStr python
- python学习的链接
- python异常
- python以gzip header请求html数据时,response内容乱码无法解码的解决方案
- python学习笔记
- python module
- python函数装饰器(decorators)
- Python中元类
- python字典
- leetcode Remove Element python
- python下载文件