Show Example 7
优质
小牛编辑
130浏览
2023-12-01
身份运算符比较两个对象的内存位置。 有两个Identity运算符,如下所述 -
操作者 | 描述 | 例 |
---|---|---|
is | 如果运算符任一侧的变量指向同一对象,则求值为true,否则求值为false。 | x是y,如果id(x)等于id(y),则结果为1。 |
is not | 如果运算符两侧的变量指向同一对象,则求值为false,否则为true。 | x不是y,如果id(x)不等于id(y),则不会产生1。 |
例子 (Example)
#!/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