The immutable object in python

后端 未结 4 502
旧时难觅i
旧时难觅i 2020-12-21 23:28

I see a article about the immutable object.

It says when:
variable = immutable
As assign the immutable to a variable.

for example

4条回答
  •  死守一世寂寞
    2020-12-21 23:56

    While that article may be correct for some languages, it's wrong for Python.

    When you do any normal assignment in Python:

    some_name = some_name_or_object
    

    You aren't making a copy of anything. You're just pointing the name at the object on the right side of the assignment.

    Mutability is irrelevant.

    More specifically, the reason:

    a = 10
    b = 10
    a is b
    

    is True, is that 10 is interned -- meaning Python keeps one 10 in memory, and anything that is set to 10 points to that same 10.

    If you do

    a = object()
    b = object()
    a is b
    

    You'll get False, but

    a = object()
    b = a
    a is b
    

    will still be True.

提交回复
热议问题