如何在Python中使用閉包和裝飾器?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
Python是一種跨平臺的、具有解釋性、編譯性、互動性和面向對象的腳本語言,其最初的設計是用于編寫自動化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發獨立的項目和大型項目。
閉包
1.函數引用
#coding=utf-8
def test1():
print('This is test1!')
#調用函數
test1()
#引用函數
ret = test1
#打?。椋?
print('test1\t的地址:',id(test1))
print('ret\t\t的地址:',id(ret))
print('你會發現test1的地址和ret的地址是一樣的!')
#通過引用調用函數
ret()運行結果:
This is test1!
test1 的地址: 139879303947128
ret 的地址: 139879303947128
你會發現test1的地址和ret的地址是一樣的!
This is test1!
1. 什么是閉包
在嵌套函數中,內部函數用到了外部函數的變量,則
稱內部函數為閉包。
python中的閉包從表現形式上定義(解釋)為:如果在一個內部函數里,對在外部作用域(但不是在全局作用域)的變量進行引用,那么內部函數就被認為是閉包(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))運行結果:
ret(20) = 30
ret(30) = 40
閉包的應用例子一:
看代碼:
#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))
運行結果:
6
25
這個例子中,函數line與變量a,b構成閉包。在創建閉包的時候,我們通過line_conf的參數a,b說明了這兩個變量的取值,這樣,我們就確定了函數的最終形式(y = x + 1和y = 4x + 5)。我們只需要變換參數a,b,就可以獲得不同的直線表達函數。由此,我們可以看到,閉包也具有提高代碼可復用性的作用。
如果沒有閉包,我們需要每次創建直線函數的時候同時說明a,b,x。這樣,我們就需要更多的參數傳遞,也減少了代碼的可移植性。
閉包思考:
1.閉包似優化了變量,原來需要類對象完成的工作,閉包也可以完成。
2.由于閉包引用了外部函數的局部變量,則外部函數的局部變量沒有及時釋放,消耗內存。
代碼如下:
#coding=utf-8 #定義函數:完成包裹數據 def makeBold(func): def wrapped(): return "<b>" + func() + "</b>" return wrapped #定義函數:完成包裹數據 def makeItalic(fn): def wrapped(): return "<i>" + fn() + "</i>" 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())
運行結果:
<b>hello world-1</b>
<i>hello world-2</i>
<b><i>hello world-3</i></b>
裝飾器(decorator)功能
1. 引入日志
2. 函數執行時間統計
3. 執行函數前預備處理
4. 執行函數后清理功能
5. 權限校驗等場景
6. 緩存
裝飾器示例
例1:無參數的函數
代碼如下:
#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()運行結果:
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:被裝飾的函數有參數
#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)運行結果:
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:被裝飾的函數有不定長參數
#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)運行結果:
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---
總結:
一般情況下為了讓裝飾器更通用,可以有return
例5:裝飾器帶參數,在原有裝飾器的基礎上,設置外部變量
#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()運行結果:
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:類裝飾器
裝飾器函數其實是這樣一個接口約束,它必須接受一個callable對象作為參數,然后返回一個callable對象。在Python中一般callable對象都是函數,但也有例外。只要某個對象重載了 call() 方法,那么這個對象就是
callable的。
class Test():
def __call__(self):
print('call me!')
t = Test()
t() # call me類裝飾器demo:
class Decofunc(object):
def __init__(self, func):
print("--初始化--")
self._func = func
def __call__(self):
print('--裝飾器中的功能--')
self._func()
@Decofunc
def showpy():
print('showpy')
showpy()#如果把這句話注釋,重新運行程序,依然會看到"--初始化--"關于如何在Python中使用閉包和裝飾器問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。