位置:首頁 > 腳本語言 > Python教學 > Python標識運算符示例

Python標識運算符示例

下表列出了所有Python語言支持的標識運算符。

運算符 描述 示例
is 計算結果為true,如果操作符兩側的變量指向相同的對象,否則為false。 x是y,這裡結果是1,如果id(x)的值為id(y)。
is not 計算結果為false,如果兩側的變量操作符指向相同的對象,否則為true。 x不為y,這裡結果不是1,當id(x)不等於id(y)。

示例:

試試下麵的例子就明白了所有Python編程語言提供的標識運算符:

#!/usr/bin/python

a = 20
b = 20

if ( a is b ):
   print "Line 1 - a and b have same identity"
else:
   print "Line 1 - a and b do not have same identity"

if ( id(a) == id(b) ):
   print "Line 2 - a and b have same identity"
else:
   print "Line 2 - a and b do not have same identity"

b = 30
if ( a is b ):
   print "Line 3 - a and b have same identity"
else:
   print "Line 3 - a and b do not have same identity"

if ( a is not b ):
   print "Line 4 - a and b do not have same identity"
else:
   print "Line 4 - a and b have same identity"

當執行上麵的程序它會產生以下結果:

Line 1 - a and b have same identity
Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity