Immutable vs Mutable types

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

    A class is immutable if each object of that class has a fixed value upon instantiation that cannot SUBSEQUENTLY be changed

    In another word change the entire value of that variable (name) or leave it alone.

    Example:

    my_string = "Hello world" 
    my_string[0] = "h"
    print my_string 
    

    you expected this to work and print hello world but this will throw the following error:

    Traceback (most recent call last):
    File "test.py", line 4, in 
    my_string[0] = "h"
    TypeError: 'str' object does not support item assignment
    

    The interpreter is saying : i can't change the first character of this string

    you will have to change the whole string in order to make it works:

    my_string = "Hello World" 
    my_string = "hello world"
    print my_string #hello world
    

    check this table:

    source

提交回复
热议问题