Immutable vs Mutable types

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

    The simplest answer:

    A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

    Example:

    >>>x = 5
    

    Will create a value 5 referenced by x

    x -> 5

    >>>y = x
    

    This statement will make y refer to 5 of x

    x -------------> 5 <-----------y

    >>>x = x + y
    

    As x being an integer (immutable type) has been rebuild.

    In the statement, the expression on RHS will result into value 10 and when this is assigned to LHS (x), x will rebuild to 10. So now

    x--------->10

    y--------->5

提交回复
热议问题