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>

posted @ 2021-10-11 11:13  嗨,阿良  阅读(52)  评论(0编辑  收藏  举报