Python3-identity-operators-example
提供:Dev Guides
Python 3-アイデンティティ演算子の例
Python組み込み関数id()は、オブジェクトのIDとして一意の整数を返します。 アイデンティティ演算子は、2つのオブジェクトのメモリ位置を比較します。 以下に説明するように、2つのアイデンティティ演算子があります-
Operator | Description | Example |
---|---|---|
is | Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. | x is y, here *is *results in 1 if id(x) equals id(y). |
is not | Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. | x is not y, here* is not* results in 1 if id(x) is not equal to id(y). |
例
#!/usr/bin/python3
a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")
出力
上記のプログラムを実行すると、次の結果が生成されます-
Line 1 a= 20 : 1594701888 b= 20 : 1594701888
Line 2 - a and b have same identity
Line 3 - a and b have same identity
Line 4 a= 20 : 1594701888 b= 30 : 1594702048
Line 5 - a and b do not have same identity