Immutable vs Mutable types

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

    A mutable object has to have at least a method able to mutate the object. For example, the list object has the append method, which will actually mutate the object:

    >>> a = [1,2,3]
    >>> a.append('hello') # `a` has mutated but is still the same object
    >>> a
    [1, 2, 3, 'hello']
    

    but the class float has no method to mutate a float object. You can do:

    >>> b = 5.0 
    >>> b = b + 0.1
    >>> b
    5.1
    

    but the = operand is not a method. It just make a bind between the variable and whatever is to the right of it, nothing else. It never changes or creates objects. It is a declaration of what the variable will point to, since now on.

    When you do b = b + 0.1 the = operand binds the variable to a new float, wich is created with te result of 5 + 0.1.

    When you assign a variable to an existent object, mutable or not, the = operand binds the variable to that object. And nothing more happens

    In either case, the = just make the bind. It doesn't change or create objects.

    When you do a = 1.0, the = operand is not wich create the float, but the 1.0 part of the line. Actually when you write 1.0 it is a shorthand for float(1.0) a constructor call returning a float object. (That is the reason why if you type 1.0 and press enter you get the "echo" 1.0 printed below; that is the return value of the constructor function you called)

    Now, if b is a float and you assign a = b, both variables are pointing to the same object, but actually the variables can't comunicate betweem themselves, because the object is inmutable, and if you do b += 1, now b point to a new object, and a is still pointing to the oldone and cannot know what b is pointing to.

    but if c is, let's say, a list, and you assign a = c, now a and c can "comunicate", because list is mutable, and if you do c.append('msg'), then just checking a you get the message.

    (By the way, every object has an unique id number asociated to, wich you can get with id(x). So you can check if an object is the same or not checking if its unique id has changed.)

提交回复
热议问题