2011/09/21

Python Decorator (裝飾)

參考資料

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)


沒有留言:

張貼留言