Why does id({}) == id({}) and id([]) == id([]) in CPython?

后端 未结 3 2194
北荒
北荒 2020-11-22 06:03

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

tuple1 = ()
tuple2 = ()                                                    


        
3条回答
  •  面向向阳花
    2020-11-22 06:30

    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.

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

提交回复
热议问题