Immutable vs Mutable types

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

    First of all, whether a class has methods or what it's class structure is has nothing to do with mutability.

    ints and floats are immutable. If I do

    a = 1
    a += 5
    

    It points the name a at a 1 somewhere in memory on the first line. On the second line, it looks up that 1, adds 5, gets 6, then points a at that 6 in memory -- it didn't change the 1 to a 6 in any way. The same logic applies to the following examples, using other immutable types:

    b = 'some string'
    b += 'some other string'
    c = ('some', 'tuple')
    c += ('some', 'other', 'tuple')
    

    For mutable types, I can do thing that actallly change the value where it's stored in memory. With:

    d = [1, 2, 3]
    

    I've created a list of the locations of 1, 2, and 3 in memory. If I then do

    e = d
    

    I just point e to the same list d points at. I can then do:

    e += [4, 5]
    

    And the list that both e and d points at will be updated to also have the locations of 4 and 5 in memory.

    If I go back to an immutable type and do that with a tuple:

    f = (1, 2, 3)
    g = f
    g += (4, 5)
    

    Then f still only points to the original tuple -- you've pointed g at an entirely new tuple.

    Now, with your example of

    class SortedKeyDict(dict):
        def __new__(cls, val):
            return dict.__new__(cls, val.clear())
    

    Where you pass

    d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))
    

    (which is a tuple of tuples) as val, you're getting an error because tuples don't have a .clear() method -- you'd have to pass dict(d) as val for it to work, in which case you'll get an empty SortedKeyDict as a result.

提交回复
热议问题