Python 简明教程
Python - Identity Operators
Python Identity Operators
同一性运算符比较对象以确定它们是否共享相同的内存并引用相同对象类型 ( data type )。
Python 提供了两个同一性运算符;我们已将其列出如下:
-
'is' Operator
-
'is not' Operator
Python 'is' Operator
如果两个操作数对象共享相同的内存位置,“ is ”运算符求值为 True。对象的内存位置可以通过“id()”函数获取。如果两个变量的“id()”相同,“is”运算符返回 True。
Example of Python Identity 'is' Operator
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a
# Comparing and printing return values
print(a is c)
print(a is b)
# Printing IDs of a, b, and c
print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))
它将生成以下 output −
True
False
id(a) : 140114091859456
id(b) : 140114091906944
id(c) : 140114091859456
Python 'is not' Operator
如果两个操作数对象不共享相同的内存位置或两个操作数不是相同对象,“ is not ”运算符求值为 True。
Example of Python Identity 'is not' Operator
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a
# Comparing and printing return values
print(a is not c)
print(a is not b)
# Printing IDs of a, b, and c
print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))
它将生成以下 output −
False
True
id(a) : 140559927442176
id(b) : 140559925598080
id(c) : 140559927442176
Python Identity Operators Examples with Explanations
Example 1
a="TutorialsPoint"
b=a
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)
它将生成以下 output −
id(a), id(b): 2739311598832 2739311598832
a is b: True
b is not a: False