本文實(shí)例講述了Python閉包和裝飾器用法。分享給大家供大家參考,具體如下:
Python的裝飾器的英文名叫Decorator,作用是完成對(duì)一些模塊的修飾。所謂修飾工作就是想給現(xiàn)有的模塊加上一些小裝飾(一些小功能,這些小功能可能好多模塊都會(huì)用到),但又不讓這個(gè)小裝飾(小功能)侵入到原有的模塊中的代碼里去。
閉包
1.函數(shù)引用
#coding=utf-8 def test1(): print('This is test1!') #調(diào)用函數(shù) test1() #引用函數(shù) ret = test1 #打印id print('test1\t的地址:',id(test1)) print('ret\t\t的地址:',id(ret)) print('你會(huì)發(fā)現(xiàn)test1的地址和ret的地址是一樣的!') #通過(guò)引用調(diào)用函數(shù) ret()
運(yùn)行結(jié)果:
This is test1!
test1?? 的地址: 139879303947128
ret???? 的地址: 139879303947128
你會(huì)發(fā)現(xiàn)test1的地址和ret的地址是一樣的!
This is test1!
1. 什么是閉包
在嵌套函數(shù)中,內(nèi)部函數(shù)用到了外部函數(shù)的變量,則
稱(chēng)內(nèi)部函數(shù)為閉包。
python中的閉包從表現(xiàn)形式上定義(解釋?zhuān)椋喝绻谝粋€(gè)內(nèi)部函數(shù)里,對(duì)在外部作用域(但不是在全局作用域)的變量進(jìn)行引用,那么內(nèi)部函數(shù)就被認(rèn)為是閉包(closure).
上代碼:
#coding=utf-8 def outer(num): def inner(num_in): return num + num_in return inner #10賦值給了num ret = outer(10) #20賦值給了num_in print('ret(20) = ',ret(20)) #30賦值給了num_in print('ret(30) = ',ret(30))
運(yùn)行結(jié)果:
ret(20) =? 30
ret(30) =? 40
閉包的應(yīng)用例子一:
看代碼:
#coding=utf-8 def line_conf(a, b): def line(x): return a*x + b return line line1 = line_conf(1, 1) line2 = line_conf(4, 5) print(line1(5)) print(line2(5))
運(yùn)行結(jié)果:
6
25
這個(gè)例子中,函數(shù)line與變量a,b構(gòu)成閉包。在創(chuàng)建閉包的時(shí)候,我們通過(guò)line_conf的參數(shù)a,b說(shuō)明了這兩個(gè)變量的取值,這樣,我們就確定了函數(shù)的最終形式(y = x + 1和y = 4x + 5)。我們只需要變換參數(shù)a,b,就可以獲得不同的直線(xiàn)表達(dá)函數(shù)。由此,我們可以看到,閉包也具有提高代碼可復(fù)用性的作用。
如果沒(méi)有閉包,我們需要每次創(chuàng)建直線(xiàn)函數(shù)的時(shí)候同時(shí)說(shuō)明a,b,x。這樣,我們就需要更多的參數(shù)傳遞,也減少了代碼的可移植性。
閉包思考:
1.閉包似優(yōu)化了變量,原來(lái)需要類(lèi)對(duì)象完成的工作,閉包也可以完成。
2.由于閉包引用了外部函數(shù)的局部變量,則外部函數(shù)的局部變量沒(méi)有及時(shí)釋放,消耗內(nèi)存。
代碼如下:
#coding=utf-8 #定義函數(shù):完成包裹數(shù)據(jù) def makeBold(func): def wrapped(): return " " + func() + " " return wrapped #定義函數(shù):完成包裹數(shù)據(jù) def makeItalic(fn): def wrapped(): return " " + fn() + " " return wrapped @makeBold def test1(): return "hello world-1" @makeItalic def test2(): return "hello world-2" @makeBold @makeItalic def test3(): return "hello world-3" print(test1()) print(test2()) print(test3())
運(yùn)行結(jié)果:
hello world-1
hello world-2
hello world-3
裝飾器(decorator)功能
1. 引入日志
2. 函數(shù)執(zhí)行時(shí)間統(tǒng)計(jì)
3. 執(zhí)行函數(shù)前預(yù)備處理
4. 執(zhí)行函數(shù)后清理功能
5. 權(quán)限校驗(yàn)等場(chǎng)景
6. 緩存
裝飾器示例
例1:無(wú)參數(shù)的函數(shù)
代碼如下:
#coding=utf-8 from time import ctime, sleep def time_func(func): def wrapped_func(): print('%s call at %s'%(func.__name__, ctime())) func() return wrapped_func @time_func def foo(): print('i am foo!') foo() sleep(2) foo()
運(yùn)行結(jié)果:
foo call at Thu Aug 24 21:32:39 2017
i am foo!
foo call at Thu Aug 24 21:32:41 2017
i am foo!
例2:被裝飾的函數(shù)有參數(shù)
#coding=utf-8 from time import ctime, sleep def timefunc(func): def wrappedfunc(a, b): print('%s called at %s'%(func.__name__, ctime())) print(a, b) func(a, b) return wrappedfunc @timefunc def foo(a,b): print(a+b) foo(3,5) sleep(2) foo(2,4)
運(yùn)行結(jié)果:
foo called at Thu Aug 24 21:40:20 2017
3 5
8
foo called at Thu Aug 24 21:40:22 2017
2 4
6
例3:被裝飾的函數(shù)有不定長(zhǎng)參數(shù)
#coding=utf-8 from time import ctime, sleep def timefunc(func): def wrappedfunc(*args, **kwargs): print('%s called at %s'%(func.__name__, ctime())) func(*args, **kwargs) return wrappedfunc @timefunc def foo(a,b,c): print(a+b+c) foo(3,5,7) sleep(2) foo(2,4,9)
運(yùn)行結(jié)果:
foo called at Thu Aug 24 21:45:13 2017
15
foo called at Thu Aug 24 21:45:15 2017
15
例4:裝飾器中的return
如下:
#coding=utf-8 from time import ctime def timefunc(func): def wrappedfunc(): print('%s called at %s'%(func.__name__, ctime())) func() return wrappedfunc @timefunc def getInfo(): return '---hello---' info = getInfo() print(info)
代碼如下:
getInfo called at Thu Aug 24 21:59:26 2017
None
如果修改裝飾器為 return func():
如下:
#coding=utf-8 from time import ctime def timefunc(func): def wrappedfunc(): print('%s called at %s'%(func.__name__, ctime())) return func() return wrappedfunc @timefunc def getInfo(): return '---hello---' info = getInfo() print(info)
代碼如下:
getInfo called at Thu Aug 24 22:07:12 2017
---hello---
總結(jié):
一般情況下為了讓裝飾器更通用,可以有return
例5:裝飾器帶參數(shù),在原有裝飾器的基礎(chǔ)上,設(shè)置外部變量
#coding=utf-8 from time import ctime, sleep def timefun_arg(pre="hello"): def timefunc(func): def wrappedfunc(): print('%s called at %s'%(func.__name__, ctime())) return func() return wrappedfunc return timefunc @timefun_arg('hello') def foo1(): print('i am foo') @timefun_arg('world') def foo2(): print('i am foo') foo1() sleep(2) foo1() foo2() sleep(2) foo2()
運(yùn)行結(jié)果:
foo1 called at Thu Aug 24 22:17:58 2017
i am foo
foo1 called at Thu Aug 24 22:18:00 2017
i am foo
foo2 called at Thu Aug 24 22:18:00 2017
i am foo
foo2 called at Thu Aug 24 22:18:02 2017
i am foo
可以理解為:
foo1()==timefun_arg("hello")(foo1()) foo2()==timefun_arg("world")(foo2())
例6:類(lèi)裝飾器
裝飾器函數(shù)其實(shí)是這樣一個(gè)接口約束,它必須接受一個(gè)callable對(duì)象作為參數(shù),然后返回一個(gè)callable對(duì)象。在Python中一般callable對(duì)象都是函數(shù),但也有例外。只要某個(gè)對(duì)象重載了 call() 方法,那么這個(gè)對(duì)象就是
callable的。 class Test(): def __call__(self): print('call me!') t = Test() t() # call me
類(lèi)裝飾器demo:
class Decofunc(object): def __init__(self, func): print("--初始化--") self._func = func def __call__(self): print('--裝飾器中的功能--') self._func() @Decofunc def showpy(): print('showpy') showpy()#如果把這句話(huà)注釋?zhuān)匦逻\(yùn)行程序,依然會(huì)看到"--初始化--"
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專(zhuān)題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
