Python 裝飾器簡單示例
簡單裝飾器示例:
def servlet(func): print("into servlet")#1 print(servlet)#2 def foo(): print("into foo")#7 print(func)#8,真正的bar函式 func()#9 print("out foo")#13 print(foo)#3 print("out servlet")#4 return foo@servletdef bar(): print("in old bar")/#0 print(bar)#11 print("out old bar")#12print(bar)#5,已經被裝飾器裝飾了bar()#6
執行順序如上,執行結果如下
into servlet.foo at 0x00000186A1801E18>out servlet .foo at 0x00000186A1801E18>into foo in old bar .foo at 0x00000186A1801E18>out old barout fooProcess finished with exit code 0
可變引數裝飾器示例:
def desc(func): print("in desc") print(desc) def foo(*arg1,**arg2): print("in foo") print(func) x = func(*arg1,**arg2) print("out foo") return x print(foo) print("out desc") return foo@descdef setArg1(x,y): print("in setArg1") print(setArg1) print("out setArg1") return x + y@descdef setArg2(x,y,z): print("in setArg2") print(setArg2) print("out setArg2") return x + y + zprint(setArg1)print(setArg2)x = setArg1(100,200)y = setArg2(100,200,300)print(x)print(y)
程式碼如上,執行結果如下
in desc.foo at 0x0000024DF2AD1E18>out descin desc .foo at 0x0000024DF2AD1EA0>out desc .foo at 0x0000024DF2AD1E18> .foo at 0x0000024DF2AD1EA0>in foo in setArg1 .foo at 0x0000024DF2AD1E18>out setArg1out fooin foo in setArg2 .foo at 0x0000024DF2AD1EA0>out setArg2out foo300600Process finished with exit code 0
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4692/viewspace-2810781/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- python裝飾器2:類裝飾器Python
- Python 裝飾器Python
- Python裝飾器Python
- 【翻譯】ECMAScript裝飾器的簡單指南
- Python 簡明教程 --- 22,Python 閉包與裝飾器Python
- 1.5.3 Python裝飾器Python
- Python 裝飾器(一)Python
- python的裝飾器Python
- Python 裝飾器原理Python
- Python裝飾器模式Python模式
- python極簡教程06:生成式和裝飾器Python
- Python深入05 裝飾器Python
- python 之裝飾器(decorator)Python
- Python中的裝飾器Python
- Python裝飾器詳解Python
- python裝飾器入門探究Python
- python 裝飾器 part2Python
- day11(python)裝飾器Python
- python中裝飾器的原理Python
- Python裝飾器高階用法Python
- python 裝飾器小白學習Python
- 【python】閉包與裝飾器Python
- Python裝飾器的前世今生Python
- python的裝飾器@的用法Python
- Python深入分享之裝飾器Python
- Python 語法之裝飾器Python
- Python3 裝飾器解析Python
- Python閉包與裝飾器Python
- Python之函式裝飾器Python函式
- python裝飾器有哪些作用Python
- python裝飾器是什麼Python
- 粗淺聊聊Python裝飾器Python
- Python迭代器&生成器&裝飾器Python
- python幾種裝飾器的用法Python
- Python學習筆記 - 裝飾器Python筆記
- Python 裝飾器你也會用Python
- Python:從閉包到裝飾器Python
- python中的裝飾器介紹Python