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 的裝飾器Python
- 簡單 12 步理解 Python 裝飾器Python
- python裝飾器2:類裝飾器Python
- 【翻譯】ECMAScript裝飾器的簡單指南
- Python裝飾器探究——裝飾器引數Python
- Python 裝飾器Python
- Python裝飾器Python
- 裝飾器 pythonPython
- Python 裝飾器裝飾類中的方法Python
- Python裝飾器模式Python模式
- python的裝飾器Python
- 1.5.3 Python裝飾器Python
- Python 裝飾器(一)Python
- Python 裝飾器原理Python
- Python 簡明教程 --- 22,Python 閉包與裝飾器Python
- python極簡教程06:生成式和裝飾器Python
- 草根學Python(十六) 裝飾器(逐步演化成裝飾器)Python
- Python函式簡單示例Python函式
- python 之裝飾器(decorator)Python
- Python深入05 裝飾器Python
- Python裝飾器詳解Python
- Python中的裝飾器Python
- 【Python】淺談裝飾器Python
- 初識Python裝飾器Python
- Python 裝飾器的理解Python
- python裝飾器介紹Python
- 淺談Python裝飾器Python
- Python3 裝飾器解析Python
- Python 語法之裝飾器Python
- Python裝飾器高階用法Python
- python裝飾器入門探究Python
- python 裝飾器 part2Python
- python裝飾器有哪些作用Python
- python裝飾器是什麼Python
- 粗淺聊聊Python裝飾器Python
- python中裝飾器的原理Python
- Python閉包與裝飾器Python
- Python之函式裝飾器Python函式