我有一个 python 哈希,其中包含函数名称到函数的映射。我想修改每个散列条目以调用关联的函数但然后也调用最终的自定义函数。它的作用有点像退出钩子。
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]()