相关疑难解决方法(0)

id()函数用于什么?

我阅读了Python 2文档并注意到了这个id()函数:

返回对象的"标识".这是一个整数(或长整数),保证在该生命周期内该对象是唯一且恒定的.具有非重叠生存期的两个对象可以具有相同的id()值.

CPython实现细节:这是内存中对象的地址.

所以,我通过使用id()列表进行了实验:

>>> list = [1,2,3]
>>> id(list[0])
31186196
>>> id(list[1])
31907092 // increased by 896
>>> id(list[2])
31907080 // decreased by 12
Run Code Online (Sandbox Code Playgroud)

函数返回的整数是多少?它是C中内存地址的同义词吗?如果是这样,为什么整数不对应于数据类型的大小?

何时id()在实践中使用?

python

93
推荐指数
6
解决办法
9万
查看次数

为什么CPython中的id({})== id({})和id([])== id([])?

为什么CPython(没有关于其他Python实现的线索)有以下行为?

tuple1 = ()
tuple2 = ()                                                                                                   
dict1 = {}
dict2 = {}
list1 = []
list2 = []
# makes sense, tuples are immutable
assert(id(tuple1) == id(tuple2))
# also makes sense dicts are mutable
assert(id(dict1) != id(dict2))
# lists are mutable too
assert(id(list1) != id(list2))
assert(id(()) == id(()))
# why no assertion error on this?
assert(id({}) == id({}))
# or this?
assert(id([]) == id([]))
Run Code Online (Sandbox Code Playgroud)

我有一些想法可能,但找不到具体原因.

编辑

进一步证明格伦和托马斯的观点:

[1] id([])
4330909912
[2] x = []
[3] …
Run Code Online (Sandbox Code Playgroud)

python identity cpython python-internals

26
推荐指数
2
解决办法
1787
查看次数

标签 统计

python ×2

cpython ×1

identity ×1

python-internals ×1