为什么在CPython中id({})== id({})和id([])== id([])? [英] Why does id({}) == id({}) and id([]) == id([]) in CPython?

查看:107
本文介绍了为什么在CPython中id({})== id({})和id([])== id([])?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么CPython(不了解其他Python实现)具有以下行为?

Why does CPython (no clue about other Python implementations) have the following behavior?

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([]))

我有一些可能的原因可以,但是找不到为什么具体

I have a few ideas why it may, but can't find a concrete reason why.

编辑

进一步证明Glenn和Thomas的观点:

To further prove Glenn's and Thomas' point:

[1] id([])
4330909912
[2] x = []
[3] id(x)
4330909912
[4] id([])
4334243440


推荐答案

CPython是一旦对象超出范围,就会对其进行垃圾回收,因此在第一个 [] 之后创建第二个 [] 被收集。因此,大多数情况下它最终都位于相同的内存位置。

CPython is garbage collecting objects as soon as they go out of scope, so the second [] is created after the first [] is collected. So, most of the time it ends up in the same memory location.

这非常清楚地显示了发生的情况(在其他Python实现中,输出可能会有所不同) :

This shows what's happening very clearly (the output is likely to be different in other implementations of Python):

class A(object):
    def __init__(self): print "a",
    def __del__(self): print "b",

# a a b b False
print A() is A()
# a b a b True
print id(A()) == id(A())

这篇关于为什么在CPython中id({})== id({})和id([])== id([])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆