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

熱線電話:13121318867

登錄
首頁精彩閱讀Python進階-函數(shù)默認參數(shù)(詳解)
Python進階-函數(shù)默認參數(shù)(詳解)
2018-08-28
收藏

Python進階-函數(shù)默認參數(shù)(詳解)

下面小編就為大家?guī)硪黄狿ython進階-函數(shù)默認參數(shù)(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一、默認參數(shù)
python為了簡化函數(shù)的調(diào)用,提供了默認參數(shù)機制:    
def pow(x, n = 2):
 
  r = 1
  while n > 0:
    r *= x
    n -= 1
  return r

這樣在調(diào)用pow函數(shù)時,就可以省略最后一個參數(shù)不寫:    
print(pow(5)) # output: 25

在定義有默認參數(shù)的函數(shù)時,需要注意以下:

必選參數(shù)必須在前面,默認參數(shù)在后;

設(shè)置何種參數(shù)為默認參數(shù)?一般來說,將參數(shù)值變化小的設(shè)置為默認參數(shù)。

python標準庫實踐

python內(nèi)建函數(shù):    
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

函數(shù)簽名可以看出,使用print('hello python')這樣的簡單調(diào)用的打印語句,實際上傳入了許多默認值,默認參數(shù)使得函數(shù)的調(diào)用變得非常簡單。

二、出錯了的默認參數(shù)

引用一個官方的經(jīng)典示例地址 :    
def bad_append(new_item, a_list=[]):
  a_list.append(new_item)
  return a_list
 
print(bad_append('1'))
print(bad_append('2'))

這個示例并沒有按照預期打印:    
['1']
['2']

而是打印了:    
['1']
['1', '2']

其實這個錯誤問題不在默認參數(shù)上,而是我們對于及默認參數(shù)的初始化的理解有誤。

三、默認參數(shù)初始化

實際上,默認參數(shù)的值只在定義時計算一次,因此每次使用默認參數(shù)調(diào)用函數(shù)時,得到的默認參數(shù)值是相同的。

我們以一個直觀的例子來說明:    
import datetime as dt
from time import sleep
 
 
def log_time(msg, time=dt.datetime.now()):
 
  sleep(1) # 線程暫停一秒
  print("%s: %s" % (time.isoformat(), msg))
 
log_time('msg 1')
log_time('msg 2')
log_time('msg 3')

運行這個程序,得到的輸出是:    
2017-05-17T12:23:46.327258: msg 1
2017-05-17T12:23:46.327258: msg 2
2017-05-17T12:23:46.327258: msg 3

即使使用了sleep(1)讓線程暫停一秒,排除了程序執(zhí)行很快的因素。輸出中三次調(diào)用打印出的時間還是相同的,即三次調(diào)用中默認參數(shù)time的值是相同的。

上面的示例或許還不能完全說明問題,以下通過觀察默認參數(shù)的內(nèi)存地址的方式來說明。

首先需要了解內(nèi)建函數(shù)id(object) :

id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

即id(object)函數(shù)返回一個對象的唯一標識。這個標識是一個在對象的生命周期期間保證唯一并且不變的整數(shù)。在重疊的生命周期中,兩個對象可能有相同的id值。
在CPython解釋器實現(xiàn)中,id(object)的值為對象的內(nèi)存地址。

如下示例使用id(object)函數(shù)清楚說明了問題:    
def bad_append(new_item, a_list=[]):
   
  print('address of a_list:', id(a_list))
  a_list.append(new_item)
  return a_list
 
print(bad_append('1'))
print(bad_append('2'))

output:
    
address of a_list: 31128072
['1']
address of a_list: 31128072
['1', '2']

兩次調(diào)用bad_append,默認參數(shù)a_list的地址是相同的。

而且a_list是可變對象,使用append方法添加新元素并不會造成list對象的重新創(chuàng)建,地址的重新分配。這樣,‘恰好'就在默認參數(shù)指向的地址處修改了對象,下一次調(diào)用再次使用這個地址時,就可以看到上一次的修改了。

那么,出現(xiàn)上述的輸出就不奇怪了,因為它們本來就是指向同一內(nèi)存地址。

四、可變與不可變默認參數(shù)

當默認參數(shù)指向可變類型對象和不可變類型對象時,會表現(xiàn)出不同的行為。

可變默認參數(shù) 的表現(xiàn)就像上訴示例一樣。

不可變默認參數(shù)

首先看一個示例:    
def immutable_test(i = 1):
  print('before operation, address of i', id(i))
  i += 1
  print('after operation, address of i', id(i))
  return i
   
print(immutable_test())
print(immutable_test())

Output:    
before operation, address of i 1470514832
after operation, address of i 1470514848
2
before operation, address of i 1470514832
after operation, address of i 1470514848
2

很明顯,第二次調(diào)用時默認參數(shù)i的值不會受第一次調(diào)用的影響。因為i指向的是不可變對象,對i的操作會造成內(nèi)存重新分配,對象重新創(chuàng)建,那么函數(shù)中i += 1之后名字i指向了另外的地址;根據(jù)默認參數(shù)的規(guī)則,下次調(diào)用時,i指向的地址還是函數(shù)定義時賦予的地址,這個地址的值1并沒有被改變。

其實,可變默認參數(shù)和不可變默認參數(shù)放在這里討論并沒太大的價值,就像其他語言中所謂的值傳遞還是引用傳遞一樣,不只會對默認參數(shù)造成影響。

五、最佳實踐

不可變的默認參數(shù)的多次調(diào)用不會造成任何影響,可變默認參數(shù)的多次調(diào)用的結(jié)果不符合預期。那么在使用可變默認參數(shù)時,就不能只在函數(shù)定義時初始化一次,而應(yīng)該在每次調(diào)用時初始化。

最佳實踐是定義函數(shù)時指定可變默認參數(shù)的值為None,在函數(shù)體內(nèi)部重新綁定默認參數(shù)的值。以下是對上面的兩個可變默認參數(shù)示例最佳實踐的應(yīng)用:    
def good_append(new_item, a_list = None):
 
  if a_list is None:
    a_list = []
 
  a_list.append(new_item)
  return a_list
 
print(good_append('1'))
print(good_append('2'))
print(good_append('c', ['a', 'b']))
    
import datetime as dt
from time import sleep
 
def log_time(msg, time = None):
 
  if time is None:
    time = dt.datetime.now()
 
  sleep(1)
  print("%s: %s" % (time.isoformat(), msg))
 
log_time('msg 1')
log_time('msg 2')
log_time('msg 3')
以上這篇Python進階-函數(shù)默認參數(shù)(詳解)就是小編分享給大家的全部內(nèi)容了

數(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); }