Python裝飾器有趣執行個體探究,python裝飾探究
廖老師的教程實在太高深,沒弄懂,點擊開啟連結
def deco_functionNeedDoc(func): if func.__doc__ == None : print func, "has no __doc__, it's a bad habit." else: print func, ':', func.__doc__, '.' return func@deco_functionNeedDocdef f(): print 'f() Do something'@deco_functionNeedDocdef g(): 'I have a __doc__' print 'g() Do something'f()g()print fprint g
這段代碼列印結果如下:
<function f at 0x0238F930> has nodoc, it's a bad habit.
<function g at 0x0238F8B0> : I have a doc .f() Do somethingg() Do something
<function f at 0x0238F930>
<function g at 0x0238F8B0>
當時我就暈菜了,想了很久,原來在@裝飾器函數的時候就會調用裝飾器,裝飾器函數return func,而func就是傳進去的參數f。這個時候把代碼改改。
def deco_functionNeedDoc(func): if func.__doc__ == None : print func, "has no __doc__, it's a bad habit." else: print func, ':', func.__doc__, '.' def func_1(*args, **kw): print func.__name__,' : this is func_1' return func_1@deco_functionNeedDocdef f(): print 'f() Do something'@deco_functionNeedDocdef g(): 'I have a __doc__' print 'g() Do something'f()g()print fprint g
此時的列印結果:
<function f at 0x023CF930> has no __doc__, it's a bad habit.
<function g at 0x023CF8B0> : I have a __doc__ .
f : this is func_1
g : this is func_1
func_1
func_1
問題至此,應該很明了了~~只是,裝飾器拿來幹嘛呢??應用在什麼情況下呢??待探索
最後再貼一個超級大團圓,太有意思了,這個不解釋了,困了,理解了這個,估摸裝飾器的基本原理就透徹了。
def deco_functionNeedDoc(func1): if func1.__name__ == "yyy" : print func1, "the func1 == yyy" else: print func1, ':', func1.__doc__, '.' def xxx() : # y + f + h + x func1() # y + f + h + f + h print "plus xxx" return func1() # y + f + h + f + h return xxxdef deco_functionNeedDocxxx(func2): if func2.__name__ == "hhh" : print func2, "the func2 == hhh" else: print func2, ':', func2.__doc__, '.' def yyy(): # y + f + h + f + h print "plus yyy" func2() # f + h return func2() # f + h return yyydef deco_functionNeedDochhh(func3): if func3.__name__ == "f" : print func3, "the func3 == f" else: print func3, ':', func3.__doc__, '.' def hhh() : # = f + h func3() # = f print "plus hhh" return "Hello Wrold" return hhh@deco_functionNeedDoc@deco_functionNeedDocxxx@deco_functionNeedDochhhdef f(): print 'print original fff'f()print "------------"print fprint "------------"print f()
結果如下:
<function f at 0x109a2b938> the func3 == f
<function hhh at 0x109a2b9b0> the func2 == hhh
<function yyy at 0x109a2ba28> the func1 == yyy
plus yyy
print original fff
plus hhh
print original fff
plus hhh
plus xxx
plus yyy
print original fff
plus hhh
print original fff
plus hhh
------------
<function xxx at 0x109a2baa0>
------------
plus yyy
print original fff
plus hhh
print original fff
plus hhh
plus xxx
plus yyy
print original fff
plus hhh
print original fff
plus hhh
Hello Wrold