美文网首页
Python JAVA immutability

Python JAVA immutability

作者: sherrysack | 来源:发表于2017-06-19 14:40 被阅读0次

    immutability

    An immutable datatype, has the property that the value of an object never changes once constructed. The downside of immutability is that a new object must be created for every value.

    Python immutable data type

    • int, float, long, complex
    • str
    • bytes
    • tuple
    • frozen set

    Python mutable data type

    • byter array
    • list
    • set
    • dict

    Difference between i+=1 and i=i+1

    method return value immutable object mutable object
    i+=1 iadd the object that was muted two methods are the same(because the old instance can't be muted, so a new one has to be created) change the object inplace and return the muted object
    i=i+1 add a new instance of sth two methods are the same create a new instance and return the new instance reference

    Example

    a = [1, 2, 3]
    b = a
    b += [1, 2, 3]
    print a  #[1, 2, 3, 1, 2, 3]
    print b  #[1, 2, 3, 1, 2, 3]
    
    a = [1, 2, 3]
    b = a
    b = b + [1, 2, 3]
    print a #[1, 2, 3]
    print b #[1, 2, 3, 1, 2, 3]

    相关文章

      网友评论

          本文标题:Python JAVA immutability

          本文链接:https://www.haomeiwen.com/subject/jmigqxtx.html