zoukankan      html  css  js  c++  java
  • 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__
        
  • 相关阅读:
    vue 零散记录
    flex布局-弹性布局
    apply 和 call 的用法
    git版本控制系统重新认识
    Windows驱动过滤--kdbclass过滤,寒江独钓加强版
    Socket的select制作多客户端传输(Qt)
    基于g_soap制作的数据下载器,传输速度只有600kb 需改进
    lua中获取数组长度问题
    MySQL存储过程详解 mysql 存储过程(转:http://blog.sina.com.cn/s/blog_52d20fbf0100ofd5.html)
    lua接受C++返回值
  • 原文地址:https://www.cnblogs.com/zengjfgit/p/5820430.html
Copyright © 2011-2022 走看看