2017-03-06 3 views
1
x = [1,2,3] 
y = x 

print(id(x)) 
print(id(y)) 
print(id(x) == id(y)) 
print(id(x) is id(y)) 

出力:パイソンID等しくない

140181905497736 
140181905497736 
True 
False 

なぜxとyのIDが同一である第1偽ですか?

+2

[Pythonの「ある」演算子を理解する]の可能複製(http://stackoverflow.com/questions/13650293/understanding-pythons-is-operator) –

答えて

0

最初の比較では2つのオブジェクトのアイデンティティを比較しますが、2番目のオブジェクトでは)関数で生成された2つの新しいオブジェクトを比較します。この例で、あなたが理解するのに役立ち、より良い:

# Here you can see that a and b are indeed the same 
>>> a = [1,2,3] 
>>> b = a 
>>> a is b 
True 
>>> id(a) == id(b) 
True 

# Now lets store id(a) and id(b). Their values should still be the same 
>>> A = id(a) 
>>> A 
4319687240 
>>> B = id(b) 
>>> B 
4319687240 
>>> A == B 
True 

# But A and B are separate objects. Which is what you compare in the second comparison 
>>> id(A) 
4319750384 
>>> id(B) 
4319750544 
>>> id(a) is id(b) 
False 
>>> A is B 
False 

# You can also see this at play if you try to print id of another id 
>>> print(id(id(a))) 
4319750416 
>>> print(id(id(a))) 
4319750512 
+0

ありがとう、これはうまく説明します! –

+0

@AlexVincentこれはまさに私の答えで言いました。また、整数が異なるアイデンティティを持つ理由を説明しません –

1

あなたがid(x) is id(y)を実行すると、オブジェクトの整数アイデンティティのアイデンティティを比較しているのではなく、リストオブジェクト自体のアイデンティティを比較しています。実装の詳細としては、integers are only cached in CPython in the range of -5 to 256id(x) == id(y)はもちろん returnsのようにreturn Trueが当然です。