• Python装饰器详解


    def html_tags(tag_name):
        print('begin outer function.')
    
        def wrapper_(func):
            print("begin of inner wrapper function.")
    
            def wrapper(*args, **kwargs):
                content = func(*args, **kwargs)
                print("<{tag}>{content}</{tag}>".format(tag=tag_name, content=content))
    
            print('end of inner wrapper function.')
            return wrapper
    
        print('end of outer function')
        return wrapper_
    
    
    # @html_tags('h1')
    def hello(name='Toby'):
        return 'Hello {}!'.format(name)
    
    
    # 1、将@html_tags('h1')换成如下表示方式:
    hello = html_tags('h1')(hello)
    
    
    # 则代码由上往下加载时,先执行html_tags('h1'),则会打印出:
    # begin outer function.
    # end of outer function
    
    # 2、执行完,将wrapper_函数返回,此时:"hello = html_tags('h1')(hello)"相当于变为:
    # "hello = wrapper_(hello)"
    
    # 3、则紧接着执行wrapper_(hello)函数,则会打印出:
    # begin of inner wrapper function.
    # end of inner wrapper function.
    
    # 4、执行完,将wrapper函数返回,此时:"hello = wrapper_(hello)"即相当于变为:
    # "hello = wrapper"
    # 而此时wrapper函数已经返回并且由'hello'变量指引。
    # wrapper函数的实现为:
    def wrapper(*args, **kwargs):
        content = hello(*args, **kwargs)
        print("<{tag}>{content}</{tag}>".format(tag='h1', content=content))
    
    
    # 5、代码接着往下加载:
    hello()
    # hello()即相当于wrapper(),则会打印出:
    # <h1>Hello Toby!</h1>
    
    # 6、代码继续往下加载:
    hello()
    # 继续调用hello()则相当于wrapper(),由于wrapper已经被hello变量所指引,现在是客观存在的函数,故:
    # 还是打印出:
    # <h1>Hello Toby!</h1>
    
    # begin outer function.
    # end of outer function
    # begin of inner wrapper function.
    # end of inner wrapper function.
    # <h1>Hello Toby!</h1>
    # <h1>Hello Toby!</h1>
    
    
    抟扶摇而上者九万里
  • 相关阅读:
    python json 和 pickle的补充 hashlib configparser logging
    go 流程语句 if goto for swich
    go array slice map make new操作
    go 基础
    块级元素 行内元素 空元素
    咽炎就医用药(慢性肥厚性咽炎)
    春季感冒是风寒还是风热(转的文章)
    秋季感冒 咳嗽 怎么选药
    解决IE浏览器“无法显示此网页”的问题
    常用的 css 样式 记录
  • 原文地址:https://www.cnblogs.com/fengting0913/p/15392497.html
Copyright © 2020-2023  润新知