is 判断两个变量是否引用同一个对象,类比java的equal(); == 判断对象的内容是否相同,类比java的==
is not判断两个变量引用自不同的对象,而 != 判断两个变量的值不同
id() 可以查看变量(或者叫对象)的内存地址,可以分析两个变量分别引用哪一个对象
import time
def log(*args, **kwargs):
print(*args, **kwargs)
# 测试id()
def test_3():
log(id(1))
log(id("abc"))
log(id([1, 2, 3]))
# 测试整数
def test_4():
x = 5000000 # 大整数
y = 5000000
log(x == y)
log(x is y)
log(id(x))
log(id(y))
# 测试字符串
def test_5():
x = "abc"
y = "abc"
log(x == y)
log(x is y)
log(id(x))
log(id(y))
# 测试list
def test_6():
x = [1, 2, 3]
y = [1, 2, 3]
log(x == y)
log(x is y)
log(id(x))
log(id(y))
# 测试tuple
def test_7():
x = (1, 2, 3)
y = (1, 2, 3)
log(x == y)
log(x is y)
log(id(x))
log(id(y))
# 测试 dict
def test_8():
x = {"id": 1, "name": "Tom", "age": 18}
y = {"id": 1, "name": "Tom", "age": 18}
log(x == y)
log(x is y)
log(id(x))
log(id(y))
# 测试set
def test_9():
x = set([1, 2, 3])
y = set([1, 2, 3])
log(x == y)
log(x is y)
log(id(x))
log(id(y))
def test_10():
x = [1, 2, 3]
y = x # 说明这里是深拷贝,y和x都指向同一个对象
log(x == y)
log(x is y)
log(id(x))
log(id(y))
if __name__ == '__main__':
# test_4()
# test_5()
# test_6()
# test_7()
# test_8()
# test_9()
test_10()
结论:
- 整数,字符串这些基础类型都是单例,值相同即引用的对象也相同
- list, tuple, dict, set这些集合即使值相同,但引用的对象都不同
- = 赋值的效果是,直接让两个变量指向同一个内存地址,即引用同一个对象