Immutable vs Mutable types

前端 未结 16 1692
感情败类
感情败类 2020-11-21 05:51

I\'m confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

class         


        
16条回答
  •  暖寄归人
    2020-11-21 06:37

    You have to understand that Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity. Other objects like integers, floats, strings and tuples are objects that can not be changed. An easy way to understand that is if you have a look at an objects ID.

    Below you see a string that is immutable. You can not change its content. It will raise a TypeError if you try to change it. Also, if we assign new content, a new object is created instead of the contents being modified.

    >>> s = "abc"
    >>>id(s)
    4702124
    >>> s[0] 
    'a'
    >>> s[0] = "o"
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'str' object does not support item assignment
    >>> s = "xyz"
    >>>id(s)
    4800100
    >>> s += "uvw"
    >>>id(s)
    4800500
    

    You can do that with a list and it will not change the objects identity

    >>> i = [1,2,3]
    >>>id(i)
    2146718700
    >>> i[0] 
    1
    >>> i[0] = 7
    >>> id(i)
    2146718700
    

    To read more about Python's data model you could have a look at the Python language reference:

    • Python 2 datamodel
    • Python 3 datamodel

提交回复
热议问题