Python3標識運算子範例

2019-10-16 23:11:47
Python 內建函式 id() 返回一個唯一的整數作為物件的身份。標識運算子比較兩個物件的儲存單元。Python有兩個標識操作符如下面所解釋:
操作符 描述 範例
is
如果操作符兩側的變數是相同的物件計算結果為true,否則返回 false
x is y,如果 id(x) 等於 id(y) ,則結果為1
is not 如果操作符兩側的變數不是相同的物件計算結果為true,否則返回 false x is y,如果 id(x) 不等於 id(y) ,則結果為1

範例

#!/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