- 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()
Example 2
在執行原始function的前與後做額外的事情
def D2(fn):
def newFn():
print "--- before do the function ---"
fn() # 此時真正去行原始function
print "--- after do the function ---"
return newFn
@D2
def f2():
print "do the f2()"
f2()
Example 3
參數檢查
def D3(fn):
def newFn(arg):
if arg <= 0:
print "err occur"
return
fn(arg)
return newFn
@D3
def f3(n):
print "%s is a positive number" % n
f3(-1)
C650FDF2BB
回覆刪除en iyi takipçi
chita swivel accent chair
699CF314
回覆刪除Muş
Balıkesir
Isparta
Tekirdağ
Van
Hakkari
Ardahan
Afyon
Rize
5D9240FB
回覆刪除Erbaa
Akçakoca
İnegöl
Erciş
Yıldırım
Bayındır
Serik
Dörtyol
Marmaris
6025F7B7
回覆刪除Aliağa
Oğuzeli
Ayaş
Çayyolu
Mudanya
Seferihisar
Çerkezköy
Bucak
Aktepe