Python 裝飾器簡單樣本

來源:互聯網
上載者:User

標籤:裝飾器

簡單裝飾器樣本:

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<function servlet at 0x00000186A1341E18><function servlet.<locals>.foo at 0x00000186A1801E18>out servlet<function servlet.<locals>.foo at 0x00000186A1801E18>into foo<function bar at 0x00000186A1801AE8>in old bar<function servlet.<locals>.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<function desc at 0x0000024DF2611E18><function desc.<locals>.foo at 0x0000024DF2AD1E18>out descin desc<function desc at 0x0000024DF2611E18><function desc.<locals>.foo at 0x0000024DF2AD1EA0>out desc<function desc.<locals>.foo at 0x0000024DF2AD1E18><function desc.<locals>.foo at 0x0000024DF2AD1EA0>in foo<function setArg1 at 0x0000024DF2AD1AE8>in setArg1<function desc.<locals>.foo at 0x0000024DF2AD1E18>out setArg1out fooin foo<function setArg2 at 0x0000024DF2AD1A60>in setArg2<function desc.<locals>.foo at 0x0000024DF2AD1EA0>out setArg2out foo300600Process finished with exit code 0

Python 裝飾器簡單樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.