Python中的裝飾器
假定現有如下需求:
def f1(x): return x*2 PRint f1(5)
那么,現在想加入一個打印日志的方法,打印出調用的是哪個方法的方法。一般做法是這樣:
def f1(x): print 'call f1()' return x*2 print f1(5)
那有沒有更簡單明了的方法呢,我上篇博文中有寫的高階函數,那么我們想到高階函數是可以把函數當參數并且可以返回函數的。那么,再次,那么,是不是可以接收一個函數,對其進行一定包裝(比如此處加一個打印日志的功能),然后返回一個新函數呢?自然可以,請看: def new_fn(f): def fn(x): print 'call'+ f.__name__+'() by decorator' return f(x) return fn f1=new_fn(f1) print f1(5)
def new_fn(f): def fn(x): print 'call' +f.__name__+'() using @' return f(x) return fn @new_fn#這里也就是相當于上面的f1=new_fn(f1)弄成了這個樣子,寫習慣了就好了。 def f1(x): return x*2 print f1(5) 
新聞熱點
疑難解答