Immutable vs Mutable types

前端 未结 16 2021
感情败类
感情败类 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:44

    In Python, there's a easy way to know:

    Immutable:

        >>> s='asd'
        >>> s is 'asd'
        True
        >>> s=None
        >>> s is None
        True
        >>> s=123
        >>> s is 123
        True
    

    Mutable:

    >>> s={}
    >>> s is {}
    False
    >>> {} is {}
    Flase
    >>> s=[1,2]
    >>> s is [1,2]
    False
    >>> s=(1,2)
    >>> s is (1,2)
    False
    

    And:

    >>> s=abs
    >>> s is abs
    True
    

    So I think built-in function is also immutable in Python.

    But I really don't understand how float works:

    >>> s=12.3
    >>> s is 12.3
    False
    >>> 12.3 is 12.3
    True
    >>> s == 12.3
    True
    >>> id(12.3)
    140241478380112
    >>> id(s)
    140241478380256
    >>> s=12.3
    >>> id(s)
    140241478380112
    >>> id(12.3)
    140241478380256
    >>> id(12.3)
    140241478380256
    

    It's so weird.

提交回复
热议问题