Skip to main content
 首页 » 编程设计

Python 嵌套函数作用域

2025年05月04日18haluo1

我有一个 python 散列,其中包含函数名称到函数的映射。我想修改每个哈希条目以调用关联的函数,然后再调用最终的自定义函数。它的作用有点像退出 Hook 。

def original(): 
    print "original work" 

成为

def replacement(): 
    original() 
    print "notify somebody..." 

我的问题是我认为我的范围界定等是错误的,因为以下代码的输出与预期不符。也许如果我可以问有没有更好的方法来做到这一点?我想坚持修改原始的 cb,因为它有第三方代码,我更改的地方越少越好。

#!/usr/bin/python  
 
def a(): 
    print "a" 
 
def b(): 
    print "b" 
 
def c(): 
    print "c" 
 
 
orig_fxn_cb = dict() 
 
" basic name to function callback hash " 
orig_fxn_cb['a'] = a 
orig_fxn_cb['b'] = b 
orig_fxn_cb['c'] = c 
 
" for each call back routine in the hash append a final action to it " 
def appendFxn(fxn_cb): 
    appended_fxn_cb_new = dict() 
    for i in orig_fxn_cb.keys(): 
        cb = fxn_cb[i] 
        def fxn_tail(): 
            cb() 
            print cb.__name__, "tail"  
 
        appended_fxn_cb_new[i] = fxn_tail 
        appended_fxn_cb_new[i]() 
    return appended_fxn_cb_new 
 
" make up a modified callback hash " 
xxx = appendFxn(orig_fxn_cb) 
print xxx 
 
for i in xxx: 
    print xxx[i]() 

请您参考如下方法:

你在追求:

from functools import wraps 
 
def notifier(f): 
    @wraps(f) 
    def wrapped(*args, **kwargs) 
        res = f(*args, **kwargs) 
        print "notify somebody..." 
        return res 
    return wrapped 
 
@notifier 
def original(): 
    print "original work" 
 
# or: original = notifier(original) 
 
original() 
original work 
notify somebody...