Python身份運算符示例

身份運算符比較兩個對象的記憶體位置。常用的有兩個身份運算符,如下所述 -

運算符 描述 示例
is 如果運算符任一側的變數指向相同的對象,則返回True,否則返回False
is not 如果運算符任一側的變數指向相同的對象,則返回True,否則返回False -

實例

#!/usr/bin/python3
#coding=utf-8
#save file : identity_operators_example.py

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")

將上面代碼保存到檔: identity_operators_example.py 中,執行結果如下 -

F:\worksp\python>python membership_operators_example.py
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list

F:\worksp\python>

上一篇: Python基本運算符 下一篇: Python決策