python 之修饰器

Posted on 2018-08-31 13:47  王将军之武库  阅读(132)  评论(0编辑  收藏  举报
from functools import update_wrapper
def debug(func):
    def wrapper():
        print "[DEBUG]: enter {}()".format(func.__name__)
        return func()
    return update_wrapper(wrapper,func)#使被修饰的函数名称不会变成wrapper

@debug
def say_hello(): #被修饰后,函数的代码会变化,先调用wrapper函数
    print "hello!"
print say_hello.__name__
def say_hello2():
    print "hello!"

say_hello()
'''
    Disassembly of module1
'''

Disassembly of debug:
 16           0 LOAD_CLOSURE             0 (func)
              3 BUILD_TUPLE              1
              6 LOAD_CONST               1 (<code object wrapper at 0129FB18, file "<module1>", line 16>)
              9 MAKE_CLOSURE             0
             12 STORE_FAST               1 (wrapper)

 19          15 LOAD_GLOBAL              0 (update_wrapper)
             18 LOAD_FAST                1 (wrapper)
             21 LOAD_DEREF               0 (func)
             24 CALL_FUNCTION            2
             27 RETURN_VALUE        

Disassembly of say_hello:
 17           0 LOAD_CONST               1 ('[DEBUG]: enter {}()')
              3 LOAD_ATTR                0 (format)
              6 LOAD_DEREF               0 (func)
              9 LOAD_ATTR                1 (__name__)
             12 CALL_FUNCTION            1
             15 PRINT_ITEM          
             16 PRINT_NEWLINE       

 18          17 LOAD_DEREF               0 (func)
             20 CALL_FUNCTION            0
             23 RETURN_VALUE        

Disassembly of say_hello2:
 26           0 LOAD_CONST               1 ('hello!')
              3 PRINT_ITEM          
              4 PRINT_NEWLINE       
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE        

 

Copyright © 2024 王将军之武库
Powered by .NET 9.0 on Kubernetes