99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁大數(shù)據(jù)時代不懂Python裝飾器,你敢說會Python?
不懂Python裝飾器,你敢說會Python?
2021-04-23
收藏

來源:麥?zhǔn)寰幊?

作者:麥?zhǔn)?

對于Python學(xué)習(xí)者,一旦過了入門階段,你幾乎一定會用到Python的裝飾器。

它經(jīng)常使用在很多地方,比如Web開發(fā),日志處理,性能搜集,權(quán)限控制等。

還有一個極其重要的地方,那就是面試的時候。對,裝飾器是面試中最常見的問題之一!

實戰(zhàn)入門

拋出問題

看這段代碼:

def step1():  print('step1.......') def step2():  print('step2......') def step3():  print('step3......')

step1()
step2()
step3()

代碼中定義了3個函數(shù),然后分別調(diào)用這3個函數(shù)。假設(shè),我們發(fā)現(xiàn)代碼運行很慢,我們想知道每個函數(shù)運行分別花了多少時間。

笨辦法解決

我們可以在每個函數(shù)中添加計時的代碼:

  • 第一行記錄開始時間
  • 執(zhí)行完業(yè)務(wù)邏輯記錄結(jié)束時間
  • 結(jié)束時間減去開始時間,算出函數(shù)執(zhí)行用時

下面的例子只在step1中添加了相關(guān)代碼作為示例,你可以自行給step2和step3添加相關(guān)代碼。

import time def step1():  start = time.time()
 print('step1.......')
 end = time.time()
 used = end - start 
 print(used) def step2():  print('step2......') def step3():  print('step3......')

step1()
step2()
step3()

這個方法可行!但用你的腳指頭想想也會覺得,這個方法很繁瑣,很笨拙,很危險!

這里只有3個函數(shù),如果有30個函數(shù),那不是要死人啦。萬一修改的時候不小心,把原來的函數(shù)給改壞了,面子都丟光了,就要被人BS了!

一定有一個更好的解決方法!

用裝飾器解決

更好的解決方法是使用裝飾器。

裝飾器并沒有什么高深的語法,它就是一個實現(xiàn)了給現(xiàn)有函數(shù)添加裝飾功能的函數(shù),僅此而已!

import time def timer(func):  '''統(tǒng)計函數(shù)運行時間的裝飾器'''  def wrapper():   start = time.time()
  func()
  end = time.time()
  used = end - start
  print(f'{func.__name__} used {used}')
 return wrapper def step1():  print('step1.......') def step2():  print('step2......') def step3():  print('step3......')

timed_step1 = timer(step1)
timed_step2 = timer(step2)
timed_step3 = timer(step3)
timed_step1()
timed_step2()
timed_step3()

上面的timer函數(shù)就是個裝飾器。

  1. 它的參數(shù)是需要被裝飾的函數(shù)
  2. 返回值是新定義的一個包裝了原有函數(shù)的函數(shù)。
  3. 新定義的函數(shù)先記錄開始時間,調(diào)用被裝飾的函數(shù),然后再計算用了多少時間。

簡單說就是把原來的函數(shù)給包了起來,在不改變原函數(shù)代碼的情況下,在外面起到了裝飾作用,這就是傳說中的裝飾器。它其實就是個普通的函數(shù)。

如果你覺得有點懵逼,需要加強一些對Python函數(shù)的理解。函數(shù):

可以作為參數(shù)傳遞

可以作為返回值

也可以定義在函數(shù)內(nèi)部

然后,我們不再直接調(diào)用step1, 而是:

  1. 先調(diào)用timer函數(shù),生成一個包裝了step1的新的函數(shù)timed_step1.
  2. 剩下的就是調(diào)用這個新的函數(shù)time_step1(),它會幫我們記錄時間。
timed_step1 = timer(step1)
timed_step1()

簡潔點,也可以這樣寫:

timer(step1)() timer(step2)() timer(step3)()

這樣可以在不修改原有函數(shù)代碼的情況下,給函數(shù)添加了裝飾性的新功能。

但是仍然需要修改調(diào)用函數(shù)的地方,看起來還不夠簡潔。有沒有更好的辦法呢?當(dāng)然是有的!

裝飾器語法糖衣

我們可以在被裝飾的函數(shù)前使用@符號指定裝飾器。這樣就不用修改調(diào)用的地方了,這個世界清凈了。下面的代碼和上一段代碼功能一樣。在運行程序的時候,Python解釋器會根據(jù)@標(biāo)注自動生成裝飾器函數(shù),并調(diào)用裝飾器函數(shù)。

import time def timer(func):  '''統(tǒng)計函數(shù)運行時間的裝飾器'''  def wrapper():   start = time.time()
  func()
  end = time.time()
  used = end - start
  print(f'{func.__name__} used {used}')
 return wrapper @timer def step1():  print('step1.......') @timer def step2():  print('step2......') @timer def step3():  print('step3......')

step1()
step2()
step3()

到了這里,裝飾器的核心概念就講完了。

剩下的基本都是在不同場合下的應(yīng)用。如果你是大忙人,不想學(xué)的太深,可以搜藏本文章,以后再回來看。

進階用法

上面是一個最簡單的例子,被裝飾的函數(shù)既沒有參數(shù),也沒有返回值。下面來看有參數(shù)和返回值的情況。

帶參數(shù)的函數(shù)

我們把step1修改一下,傳入一個參數(shù),表示要走幾步。

import time def timer(func):  '''統(tǒng)計函數(shù)運行時間的裝飾器'''  def wrapper():   start = time.time()
  func()
  end = time.time()
  used = end - start
  print(f'{func.__name__} used {used}')
 return wrapper @timer def step1(num):  print(f'我走了#{num}步')

step1(5)

再去運行,就報錯了:

TypeError: wrapper() takes 0 positional arguments but 1 was given

這是因為,表面上我們寫的是step1(5),實際上Python是先調(diào)用wrapper()函數(shù)。這個函數(shù)不接受參數(shù),所以報錯了。

為了解決這個問題,我們只要給wrapper加上參數(shù)就可以。

import time def timer(func):  '''統(tǒng)計函數(shù)運行時間的裝飾器'''  def wrapper(*args, **kwargs):   start = time.time()
  func(*args, **kwargs)
  end = time.time()
  used = end - start
  print(f'{func.__name__} used {used}')
 return wrapper
  1. wrapper使用了通配符,*args代表所有的位置參數(shù),**kwargs代表所有的關(guān)鍵詞參數(shù)。這樣就可以應(yīng)對任何參數(shù)情況。
  2. wrapper調(diào)用被裝飾的函數(shù)的時候,只要原封不動的把參數(shù)再傳遞進去就可以了。

函數(shù)返回值

如果被裝飾的函數(shù)func有返回值,wrapper也只需把func的返回值返回就可以了。

import time def timer(func):  '''統(tǒng)計函數(shù)運行時間的裝飾器'''  def wrapper(*args, **kwargs):   start = time.time()
  ret_value = func(*args, **kwargs)
  end = time.time()
  used = end - start
  print(f'{func.__name__} used {used}')
  return ret_value
 return wrapper @timer def add(num1, num2):  return num1 + num2

sum = add(58)
print(sum)

這里我新加了一個add函數(shù),計算兩個數(shù)之和。

在wrapper函數(shù)中,我們先保存了func的返回值到ret_value,然后在wrapper的最后返回這個值就可以了。

到這里,你又進了一步,你可以擊敗88.64%的Python學(xué)習(xí)者了。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }