Python的decorator学习笔记
2015-11-26 14:46
453 查看
今天将python的decorator系统地学习了一下,自己也试着写了下,共有三种类型,第一种是普通装饰器,不带参数也不带返回值的。只需要将func(*args, **kwargs)在闭包函数块儿里执行就行,这是一定要执行的,不然就会返回与原来函数没有任何关系的函数了,甚至报错。同时如果是用decorator,那么原来函数的函数名字就变成了wrapper
的名字,这时,需要我们将原来的和wrapper的函数名字对调过来才行,如用@wrap(func)或者是return functools.update_wrapper(wrapper, func)这样的语句将其调换过来,这样函数的名字就和原来的一模一样了,不会再以后的使用中出错。有参数的decorator,就是多了一层嵌套,最外面的是传入参数的函数,里面嵌套原来的不带参数的decorator,最后将那个decorator返回就行。最后是被装饰的函数有返回值的情况,将func的结果赋值给result, 最后将result返回出去即可。下面是自己讲各种情况都试了下的代码,自己当笔记。
python的装饰器在编程里使用时,可以高效地减少一些重复的工作。
参考文章:
http://www.ibm.com/developerworks/cn/linux/l-cpdecor.html http://www.cnblogs.com/jerry-Chou/archive/2012/05/23/python-decorator-explain.html
感谢机器猫的文章
的名字,这时,需要我们将原来的和wrapper的函数名字对调过来才行,如用@wrap(func)或者是return functools.update_wrapper(wrapper, func)这样的语句将其调换过来,这样函数的名字就和原来的一模一样了,不会再以后的使用中出错。有参数的decorator,就是多了一层嵌套,最外面的是传入参数的函数,里面嵌套原来的不带参数的decorator,最后将那个decorator返回就行。最后是被装饰的函数有返回值的情况,将func的结果赋值给result, 最后将result返回出去即可。下面是自己讲各种情况都试了下的代码,自己当笔记。
# __author__ = 'lulongfei' from functools import wraps import functools ''' common decorator no args no return result ''' def my_decortor(func): @wraps(func) def wrapper(*args, **kwargs): print ('Calling decorated function') return func(*args, **kwargs) return wrapper @my_decortor def example(): '''Docstring''' print ('Called example function') example() example.__name__ ''' decorator have args ''' def log(text): def decorator(func): def wrapper(*args, **kwargs): print '%s%s():'%(text, func.__name__) return func(*args, **kwargs) return wrapper return decorator @log('my_decorator:') def example(): '''Docstring''' print ('Called example function') example() def spamdef(fn): def wrapper(*args): print "spam, spam, spam" return fn(*args) return wrapper @spamdef def useful(a, b): print a**2 + b**2 useful(3, 4) def arg_sayer(what): def what_sayer(meth): def new(self, *args, **kwargs): print what return meth(self, *args, **kwargs) return new return what_sayer def FooMaker(word): class Foo(object): @arg_sayer def say(self):pass return Foo() foo1 = FooMaker('this') foo2 = FooMaker('that') print type(foo1) foo1.say() def flaz(self):return 'flaz' def flam(self):return 'flam' def change_method(new): '''waring: only decorate the __new__() method with this decorator''' if new.__new__ != '__new__': return new def __new__(cls, *args, **kwargs): cls.flaz = flaz cla.flam = flam if hasattr(cls, 'say'):del cls.say return super(cls.__class__, cls).__new__(cls, *args, **kwargs) return __new__ class Foo(object): @change_method def __new__():pass def say(self):print 'Hi me:', self foo = Foo() print foo.flaz() foo.say() '''decortor include the return result''' def printdebug(func): def decorator(user): print ('enter the login') result = func(user) print ('exit the login') return result return decorator @printdebug def login(user): print ('in login:' + user) msg = "success" if user == "chuck" else "bruno" return msg result1 = login("chuck") print result1
python的装饰器在编程里使用时,可以高效地减少一些重复的工作。
参考文章:
http://www.ibm.com/developerworks/cn/linux/l-cpdecor.html http://www.cnblogs.com/jerry-Chou/archive/2012/05/23/python-decorator-explain.html
感谢机器猫的文章
相关文章推荐
- 11.26-----总结前天的Python(x,y)的安装以及Anaconda,Theano的安装。
- 机器学习实战python版决策树以及Matplotlib注解绘制决策树
- python内置函数__init__及__str__的区别
- 认真学习python,从第一篇博客开始
- python IP 处理模块IPy
- selenium 2 + python 窗口定位
- python cvs文件处理脚本 python csv
- Python笔记 基础篇2
- Python笔记 基础篇1
- python爬虫环境搭建
- Python常见第一个错误
- Python2.7本地发布模块(modules)笔记
- PEP8 Python 编码规范
- python
- Python + Scrapy 小小爬虫有大大梦想
- Visual Studio 2012 Ultimate 上安装 Python 开发插件 PTVS
- pymol png python 不输出图片 ray解决方法 ,
- python中os.listdir的排序问题
- ipython notebook使用教程
- ipython notebook使用教程