Immutable vs Mutable types

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

    I haven't read all the answers, but the selected answer is not correct and I think the author has an idea that being able to reassign a variable means that whatever datatype is mutable. That is not the case. Mutability has to do with passing by reference rather than passing by value.

    Lets say you created a List

    a = [1,2]
    

    If you were to say:

    b = a
    b[1] = 3
    

    Even though you reassigned a value on B, it will also reassign the value on a. Its because when you assign "b = a". You are passing the "Reference" to the object rather than a copy of the value. This is not the case with strings, floats etc. This makes list, dictionaries and the likes mutable, but booleans, floats etc immutable.

提交回复
热议问题