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>
    
    
    抟扶摇而上者九万里
  • 相关阅读:
    构建maven的web项目时注意的问题(出现Error configuring application listener of class org.springframework.web.context.ContextLoaderListener 或者前端控制器无法加载)
    c3p0私有属性checkoutTimeout设置成1000引发的调试错误:
    sql面试题(学生表_课程表_成绩表_教师表)
    传值与传址
    new String()理解
    hashcode的理解
    CentOs安装ssh服务
    openstack swift memcached
    openstack swift middleware开发
    java实现二叉树
  • 原文地址:https://www.cnblogs.com/fengting0913/p/15392497.html
Copyright © 2011-2022 走看看