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