溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何實現(xiàn)Python閉包與裝飾器

發(fā)布時間:2020-07-29 11:20:08 來源:億速云 閱讀:177 作者:小豬 欄目:開發(fā)技術(shù)

這篇文章主要講解了如何實現(xiàn)Python閉包與裝飾器,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

一、閉包

閉包相當(dāng)于函數(shù)中,嵌套另一個函數(shù),并返回。代碼如下:

def func(name): # 定義外層函數(shù)
  def inner_func(age): # 內(nèi)層函數(shù)
    print('name: ', name, ', age: ', age)
  return inner_func # 注意此處要返回,才能體現(xiàn)閉包

bb = func('jayson') # 將字符串傳給func函數(shù),返回inner_func并賦值給變量
bb(28) # 通過變量調(diào)用func函數(shù),傳入?yún)?shù),從而完成閉包
>>
name: jayson , age: 28

二、裝飾器

裝飾器:把函數(shù)test當(dāng)成變量傳入裝飾函數(shù)deco --> 執(zhí)行了裝飾操作后,變量傳回給了函數(shù)test()。比如裝飾器效果是test = test-1,test函數(shù)經(jīng)過deco裝飾后,調(diào)用test其實執(zhí)行的是 test = test-1。

1、裝飾器是利用閉包原理,區(qū)別是裝飾器在閉包中傳入的參數(shù)是函數(shù),而不是變量。

注:其實在裝飾器中,函數(shù)即變量

def deco(func): # 傳入func函數(shù)。
  print('decoration')
  return func
def test():
  print('test_func')

test = deco(test) # 對函數(shù)進(jìn)行裝飾。執(zhí)行了deco函數(shù),并將返回值賦值給test
>>
# 輸出deco的運(yùn)行結(jié)果
decoration

test() # 運(yùn)行裝飾后的函數(shù)
>>
test_func

2、以上代碼等價于

def deco(func): # 傳入func函數(shù)。
  print('decoration')
  return func

@deco # 等價于上一代碼中test = deco(test),不過上一代碼需放在定義test之后
def test():
  print('test_func')

>>
# 輸出deco的運(yùn)行結(jié)果
decoration

test() # 運(yùn)行裝飾后的函數(shù)
>>
test_func

3、裝飾器(簡版)

def deco(func): # 裝飾函數(shù)傳入func
  print('decoration')
  return func

@deco # 裝飾函數(shù)。
def test():
  print('test_func') 
# 定義完函數(shù)后,會直接執(zhí)行裝飾器deco(test)
>>
decoration

# 調(diào)用test,執(zhí)行test函數(shù)
test()
>> 
test_func

3、裝飾器(升級版)

在上一個版本中,由于在定義裝飾器 + 函數(shù)時,就會執(zhí)行裝飾函數(shù)里面的語句。

為了使其在未被調(diào)用時候不執(zhí)行,需要再嵌套一個函數(shù),將函數(shù)進(jìn)行包裹。

def deco(func): 
  print('decoration') # 此處未調(diào)用func函數(shù)時,會直接執(zhí)行
  def wrapper(): # 名稱自定義,一般用wrapper
    print('execute') # 此處未調(diào)用func函數(shù)時,不會執(zhí)行
    func() # 執(zhí)行函數(shù)
  return wrapper # 此處返回wrapper給func,通過外部func()執(zhí)行

@deco # 注意:此處不能有括號。有括號的形式是func未傳入最外層deco(),傳入deco的子函數(shù)中
def test():
  print('test_func')
>>
decoration
#調(diào)用test
test()
>>
execute
test_func

注意:如果func函數(shù)本身有返回值,同樣需要在包裹函數(shù)中返回

def deco(func): 
  print('decoration')
  def wrapper():
    print('execute')
    a = func() # 執(zhí)行函數(shù),并返回值
    print('done')
    return a # 將func的返回值一并返回
  return wrapper

@deco
def test():
  print('test_func')
  return 5 # 增加返回值
>>
decoration

#調(diào)用test
test()
>>
execute
test_func
done
 # 此處是test函數(shù)的返回值

3、裝飾器(進(jìn)階版)

在包裹函數(shù)中,參數(shù)形式設(shè)置為*arg、**kwarg,會使得函數(shù)更加靈活。

當(dāng)修改test函數(shù)參數(shù)形式時,不用在裝飾器中同時修改。

import time

def deco(func):
  def inner(*arg, **kwarg): # 此處傳入?yún)?shù)
    begin_time = time.time()
    time.sleep(2)
    a = func(*arg, **kwarg) # 調(diào)用函數(shù),使用傳入的參數(shù)
    end_time = time.time()
    print('運(yùn)行時間:', end_time - begin_time)
    return a
  return inner

@deco
def test(a):
  print('test function:', a)
  return a

# 調(diào)用函數(shù)
test(5)
>>
test function: 5
運(yùn)行時間: 2.0003252029418945
 # 5是函數(shù)返回的值

4、高階版

有時候我們會發(fā)現(xiàn)有的裝飾器帶括號,其原因是將上述的裝飾器外面又套了一個函數(shù)

import time

def outer(): # 在原裝飾器外套一層函數(shù),將裝飾器封裝在函數(shù)里面。(outer自定義)
  def deco(func): # 原裝飾器,后面的代碼一樣
    def inner(*arg, **kwarg): 
      begin_time = time.time()
      time.sleep(2)
      a = func(*arg, **kwarg) 
      end_time = time.time()
      print('運(yùn)行時間:', end_time - begin_time)
      return a
    return inner
  return deco # 注意:此處需返回裝飾函數(shù)

@outer() # 此處就需要加括號,其實是調(diào)用了outer()函數(shù),將test傳進(jìn)其子函數(shù)
def test(a):
  print('test function:', a)
  return a

test(4)
>>
test function: 4
運(yùn)行時間: 2.000566005706787
 # 返回4

5、高階終結(jié)版

帶參數(shù)的裝飾器(裝飾器加括號,帶參數(shù))

import time

def outer(choose): # 在最外層函數(shù)中加入?yún)?shù)
  if choose==1: # 通過choose參數(shù),選擇裝飾器
    def deco(func):
      def inner(*arg, **kwarg):
        print('decoration1')
        begin_time = time.time()
        time.sleep(2) # 睡眠2s
        a = func(*arg, **kwarg) 
        end_time = time.time()
        print('運(yùn)行時間1:', end_time - begin_time)
        return a
      return inner
    return deco
  
  else:
    def deco(func):
      def inner(*arg, **kwarg): 
        print('decoration2')
        begin_time = time.time()
        time.sleep(5) # 睡眠5s
        a = func(*arg, **kwarg) 
        end_time = time.time()
        print('運(yùn)行時間2:', end_time - begin_time)
        return a
      return inner
    return deco

@outer(1) # 由于outer中有參數(shù),此處必須傳入?yún)?shù)
def test1(a):
  print('test function1:', a)
  return a

@outer(5) # 傳入另一個參數(shù)
def test2(a):
  print('test function2:', a)
  return a


# 分別調(diào)用2個函數(shù)(2個函數(shù)裝飾器相同,裝飾器參數(shù)不同)
test1(2) # 調(diào)用test1
>>
decoration1
test function1: 2
運(yùn)行時間1: 2.000072717666626 # 2秒
 # test1的返回值

test2(4) # 調(diào)用test2
>>
decoration2
test function2: 4
運(yùn)行時間2: 5.000797986984253 # 5秒
 # test2的返回值

看完上述內(nèi)容,是不是對如何實現(xiàn)Python閉包與裝飾器有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI