本文實例講述了Python中的is和id用法。分享給大家供大家參考。具體分析如下:
(ob1 is ob2) 等價于 (id(ob1) == id(ob2))
首先id函數可以獲得對象的內存地址,如果兩個對象的內存地址是一樣的,那么這兩個對象肯定是一個對象。和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;
但是請看下邊代碼的這種情況怎么會出現呢?
代碼如下: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,這與我們已知的事實不符啊,這種現象該如何解釋呢?遇到這種情況最好的解決方法就是調用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
|
新聞熱點
疑難解答