zoukankan      html  css  js  c++  java
  • 【易混淆】1-is 和 == , is not 与 !=

    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这些集合即使值相同,但引用的对象都不同
    • = 赋值的效果是,直接让两个变量指向同一个内存地址,即引用同一个对象
  • 相关阅读:
    Win8 iis 环境搭建
    Windows phone 8 触发器使用小结
    Windows Phone 页面之间参数传递方法
    日期SQL 脚本
    net 内存泄露和内存溢出
    Emacs的一些事情(与Vi的争议及使用)
    matlab与示波器连接及电脑连接
    msp430学习笔记-TA
    28个Unix/Linux的命令行神器
    linux在线中文手册
  • 原文地址:https://www.cnblogs.com/LS1314/p/8504695.html
Copyright © 2011-2022 走看看