python 闭包、注入、装饰

##-coding:utf-8-##
def html_tags(tag_name):
    print
    print 'call html_tags(tag_name): ' + tag_name
    def wrapper_(func):
        print "\tcall warpper_(func): " + func.__name__ +" " + str(type(func))
​
        def wrapper(*args, **kwargs):
            print "\t\tcall wrapper(*args, **kwargs): " + args.__str__() + ", " + kwargs.__str__()
            print "\t\t\ttag_name: " + tag_name + ", callfunc: " + func.__name__
            content = func(*args, **kwargs)
            return "<{tag}>{content}</{tag}>".format(tag=tag_name, content=content)
        return wrapper
​
    return wrapper_
​
#   @html_tags('c') 相当于执行了hello = html_tag('c')(hello),注入进去,返回一个匿名函数hello,
# print hello('word1')相当于执行 hello('word1')
@html_tags('c')       #hello = html_tag('c')(hello)
def hello(name='Toby'):
    return 'Hello {}!'.format(name)
print hello('word1')  #hello('word')
​
res = html_tags('b')(hello)     #由于有@html_tag装饰,hello = html_tag('c')(hello)已经执行,res已经注入进去
print res('test1')
​
res = html_tags('a')(res)       #注入上一个, 函数栈,如果不是res而hello,将注入c而不是b
print res('test2')
​
print "\n这是hello('word2')调用"
print hello('word2')  #hello('word2')
​
@html_tags('d')
def demo(name='test3'):
    return 'Hello {}!'.format(name)
print demo('word3')
​
exit()

结果:/usr/bin/python demo.py

call html_tags(tag_name): c
     call warpper_(func): hello <type 'function'>
          call wrapper(*args, **kwargs): ('word1',), {}
               tag_name: c, callfunc: hello
<c>Hello word1!</c>
​
call html_tags(tag_name): b
     call warpper_(func): wrapper <type 'function'>
          call wrapper(*args, **kwargs): ('test1',), {}
               tag_name: b, callfunc: wrapper
          call wrapper(*args, **kwargs): ('test1',), {}
               tag_name: c, callfunc: hello
<b><c>Hello test1!</c></b>
​
call html_tags(tag_name): a
     call warpper_(func): wrapper <type 'function'>
          call wrapper(*args, **kwargs): ('test2',), {}
               tag_name: a, callfunc: wrapper
          call wrapper(*args, **kwargs): ('test2',), {}
               tag_name: b, callfunc: wrapper
          call wrapper(*args, **kwargs): ('test2',), {}
               tag_name: c, callfunc: hello
<a><b><c>Hello test2!</c></b></a>
​
这是hello('word2')调用
          call wrapper(*args, **kwargs): ('word2',), {}
               tag_name: c, callfunc: hello
<c>Hello word2!</c>
​
call html_tags(tag_name): d
     call warpper_(func): demo <type 'function'>
          call wrapper(*args, **kwargs): ('word3',), {}
               tag_name: d, callfunc: demo
<d>Hello word3!</d>
​
Process finished with exit code 0

http://51strive.com/doc/201611301306.html

    原文作者:onefishum
    原文地址: https://www.jianshu.com/p/5c6af34b050a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞