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

熱線電話:13121318867

登錄
首頁精彩閱讀舉例講解Python中is和id的用法
舉例講解Python中is和id的用法
2018-04-30
收藏

舉例講解Python中is和id的用法

(ob1 is ob2) 等價于 (id(ob1) == id(ob2))

首先id函數(shù)可以獲得對象的內存地址,如果兩個對象的內存地址是一樣的,那么這兩個對象肯定是一個對象。和is是等價的。Python源代碼為證。    
static PyObject *
 cmp_outcome(int op, register PyObject *v, register PyObject *w)
{
 int res = 0;
 switch (op) {
 case PyCmp_IS:
 res = (v == w);
 break;
 case PyCmp_IS_NOT:
res = (v != w);
 break;

但是請看下邊代碼的這種情況怎么會出現(xiàn)呢?
    
In [1]: def bar(self, x):
...:   return self.x + y
...:
 
In [2]: class Foo(object):
...:   x = 9
...:   def __init__(self ,x):
...:     self.x = x
...:   bar = bar
...:  
 
In [3]: foo = Foo(5)
 
In [4]: foo.bar is Foo.bar
Out[4]: False
 
In [5]: id(foo.bar) == id(Foo.bar)
Out[5]: True

兩個對象用is判斷是False,用id判斷卻是True,這與我們已知的事實不符啊,這種現(xiàn)象該如何解釋呢?遇到這種情況最好的解決方法就是調用dis模塊去看下兩個比較語句到底做了什么。
    
In [7]: dis.dis("id(foo.bar) == id(Foo.bar)")
     0 BUILD_MAP    10340
     3 BUILD_TUPLE   28527
     6 <46>     
     7 DELETE_GLOBAL  29281 (29281)
     10 STORE_SLICE+1
     11 SLICE+2   
     12 DELETE_SUBSCR
     13 DELETE_SUBSCR
     14 SLICE+2   
     15 BUILD_MAP    10340
     18 PRINT_EXPR  
     19 JUMP_IF_FALSE_OR_POP 11887
     22 DELETE_GLOBAL  29281 (29281)
     25 STORE_SLICE+1
 
In [8]: dis.dis("foo.bar is Foo.bar")
     0 BUILD_TUPLE   28527
     3 <46>     
     4 DELETE_GLOBAL  29281 (29281)
     7 SLICE+2   
     8 BUILD_MAP    8307
     11 PRINT_EXPR  
     12 JUMP_IF_FALSE_OR_POP 11887
     15 DELETE_GLOBAL  29281 (29281)

真實情況是當執(zhí)行.操作符的時候,實際是生成了一個proxy對象,foo.bar is Foo.bar的時候,兩個對象順序生成,放在棧里相比較,由于地址不同肯定是False,但是id(foo.bar) == id(Foo.bar)的時候就不同了,首先生成foo.bar,然后計算foo.bar的地址,計算完之后foo.bar的地址之后,就沒有任何對象指向foo.bar了,所以foo.bar對象就會被釋放。然后生成Foo.bar對象,由于foo.bar和Foo.bar所占用的內存大小是一樣的,所以又恰好重用了原先foo.bar的內存地址,所以id(foo.bar) == id(Foo.bar)的結果是True。

下面內容由郵件Leo Jay大牛提供,他解釋的更加通透。

用id(expression a) == id(expression b)來判斷兩個表達式的結果是不是同一個對象的想法是有問題的。

foo.bar 這種形式叫 attribute reference [1],它是表達式的一種。foo是一個instance object,bar是一個方法,這個時候表達式foo.bar返回的結果叫method object [2]。根據(jù)文檔:

    When an instance attribute is referenced that isn't a data attribute,
    its class is searched. If the name denotes a valid class attribute
    that is a function object, a method object is created by packing
    (pointers to) the instance object and the function object just found
    together in an abstract object: this is the method object.

foo.bar本身并不是簡單的名字,而是表達式的計算結果,是一個 method object,在id(foo.bar)這樣的表達式里,method object只是一個臨時的中間變量而已,對臨時的中間變量做id是沒有意義的。
一個更明顯的例子是,    
print id(foo.bar) == id(foo.__init__)

輸出的結果也是True

看 id 的文檔[3]:

    Return the “identity” of an object. This is an integer (or long
    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 來比較兩個對象。所以,如果你非要比的話,得這樣寫:    
fb = foo.bar
Fb = Foo.bar
print id(fb) == id(Fb)

即把兩個表達式的結果綁定到名字上,再來比是不是同一個對象,你才能得到正確的結果。

is表達式 [4] 也是一樣的,你現(xiàn)在得到了正確的結果,完全是因為 CPython 現(xiàn)在的實現(xiàn)細節(jié)決定的?,F(xiàn)在的is的實現(xiàn),是左右兩邊的對象都計算出來,然后再比較這兩個對象的地址是否一樣。萬一哪天改成了,先算左邊,保存地址,把左邊釋放掉,再算右邊,再比較的話,你的is的結果可能就錯了。官方文檔里也提到了這個問題 [5]。我認為正確的方法也是像id那樣,先把左右兩邊都計算下來,并顯式綁定到各自的名字上,然后再用is判斷。

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

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

數(shù)據(jù)分析師考試動態(tài)
數(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(); // 調用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調,回調的第一個參數(shù)驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 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); }