我有一個python哈希,它包含函數名稱映射到函數。我想修改每個散列條目來調用相關的函數BUT,然後調用最終的自定義函數。這有點像退出鉤子。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]()
如果我可以,你的變量名稱不是最具描述性的。這肯定會讓我們難以跟蹤發生的事情。 – jathanism
如何使用裝飾器? – jterrace
@jterrace我會張貼作爲答案。 –