- Design Pattern: Decorator 模式 - From Gossip@caterpillar
- [Python学习]decorator的使用 - 在文中有提到幾個應用時機:
- 針對某function執行前做一些工作。如:在Web開發中,很多頁面都需要user登入後才可access,可以使用decorator來檢查user session
- 針對某function執行後做一些工作。如:針對function的return code來寫log
- Understanding Python decorators - 這個是我看過眾多範例中最簡單的一個,我也是從這邊學會的。
Example 1
在原始function的return值做裝飾
def D1(fn):
def newFn():
return "" + fn() + ""
return newFn
@D1
def f1():
return "a sentence"
print f1()

