zoukankan      html  css  js  c++  java
  • 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>
    
    
    抟扶摇而上者九万里
  • 相关阅读:
    web框架和Django框架的初识
    外键的变种,单表的查询,多表的查询
    数据库的安装与初识
    响应式设计中几个class区别
    Velocity+Java较全教程
    Web开发基础
    AutoCompleteTextView不能使用的问题
    Http中Cookie与Set-Cookie头
    Java Web 乱码
    Karel运行环境配置
  • 原文地址:https://www.cnblogs.com/fengting0913/p/15392497.html
Copyright © 2011-2022 走看看