Immutable vs Mutable types

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

    What? Floats are immutable? But can't I do

    x = 5.0
    x += 7.0
    print x # 12.0
    

    Doesn't that "mut" x?

    Well you agree strings are immutable right? But you can do the same thing.

    s = 'foo'
    s += 'bar'
    print s # foobar
    

    The value of the variable changes, but it changes by changing what the variable refers to. A mutable type can change that way, and it can also change "in place".

    Here is the difference.

    x = something # immutable type
    print x
    func(x)
    print x # prints the same thing
    
    x = something # mutable type
    print x
    func(x)
    print x # might print something different
    
    x = something # immutable type
    y = x
    print x
    # some statement that operates on y
    print x # prints the same thing
    
    x = something # mutable type
    y = x
    print x
    # some statement that operates on y
    print x # might print something different
    

    Concrete examples

    x = 'foo'
    y = x
    print x # foo
    y += 'bar'
    print x # foo
    
    x = [1, 2, 3]
    y = x
    print x # [1, 2, 3]
    y += [3, 2, 1]
    print x # [1, 2, 3, 3, 2, 1]
    
    def func(val):
        val += 'bar'
    
    x = 'foo'
    print x # foo
    func(x)
    print x # foo
    
    def func(val):
        val += [3, 2, 1]
    
    x = [1, 2, 3]
    print x # [1, 2, 3]
    func(x)
    print x # [1, 2, 3, 3, 2, 1]
    

提交回复
热议问题