python中的id()函数及读取list的方法介绍(代码示例)

python教程评论323 views阅读模式

本篇文章给大家带来的内容是关于python中的id()函数及读取list的方法介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

id(object)

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.

说起这个函数就需要先了解pyhton的变量存储机制了:
变量:是动态变量,不用提前声明类型。

当我们写:a = 'ABC'时,Python解释器干了两件事情:

  1. 在内存中创建了一个'ABC'的字符串;

  2. 在内存中创建了一个名为a的变量,并把它指向'ABC'。

id(a)读取的是a的内存地址

程序范例

def addElement(_list):
    print(6,id(_list))
    _list.append(0)
    print(7,id(_list))
    return _list

if __name__=="__main__":
    list1=[1,2,3]
    print(1,id(list1))
    list2 = addElement(list1)
    print(2,list1)
    print(3,id(list1))
    print(4,list2)
    print(5,id(list2))

执行结果:

(1, 48757192L)
(6, 48757192L)
(7, 48757192L)
(2, [1, 2, 3, 0])
(3, 48757192L)
(4, [1, 2, 3, 0])
(5, 48757192L)

两个要点:

  1. return语句返回后list1就已经变为其返回值而不是原来的值

  2. 自从定义后list1这个变量的本质就是一个内存盒子,传到函数里面的一直是这个变量本身,所以地址没变,最后返回的还是他,只是后面加了一个新值,而用a=b这种赋值方法后ab的内存地址是一致的。因此从头到尾list1,list2,_list内存地址都没变过

以上就是python中的id()函数及读取list的方法介绍(代码示例)的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2019年9月8日 01:11:55
  • 转载请务必保留本文链接:https://www.qieseo.com/348029.html

发表评论