Python Decorator

/*********************************************************************************
 *                              Python Decorator
 * 说明:
 *     最近要处理markdown文档,想使用mkdocs来做实时修改显示,但其界面的pages设定
 * 总让我这边不是很舒服,不能隐藏,所以打算看一下其源代码,看能不能隐藏,先学习
 * 一下Python修饰器的语法,原因是源代码里面用到了修饰器。
 *
 *                                                2016-8-30 深圳 南山平山村 曾剑锋
 *********************************************************************************/

一、参考文档:
    1. A guide to Python's function decorators
        http://thecodeship.com/patterns/guide-to-python-function-decorators/
    2. Python天天美味(34) - Decorators详解
        http://www.cnblogs.com/coderzh/archive/2010/04/27/python-cookbook33-decorators.html
    3. Python Decorator的来龙
        https://segmentfault.com/a/1190000003719779
    4. 装饰器
        http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000

二、示例1:
    def p_decorate(func):
       def func_wrapper(name):
           return "<p>{0}</p>".format(func(name))
       return func_wrapper

    @p_decorate
    def get_text(name):
       return "lorem ipsum, {0} dolor sit amet".format(name)

    print get_text("John")
    # Outputs <p>lorem ipsum, John dolor sit amet</p>

三、示例2:
    from functools import wraps

    def tags(tag_name):
        def tags_decorator(func):
            @wraps(func)
            def func_wrapper(name):
                return "<{0}>{1}</{0}>".format(tag_name, func(name))
            return func_wrapper
        return tags_decorator

    @tags("p")
    def get_text(name):
        """returns some text"""
        return "Hello "+name

    print get_text.__name__ # get_text
    print get_text.__doc__ # returns some text
    print get_text.__module__ # __main__
    

 

posted on 2016-08-30 07:20  zengjf  阅读(259)  评论(0编辑  收藏  举报

导航