Mutability Vs Immutability

Python 2 datamodel
The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity. Other objects like numbers, strings and tuples ... are objects that can not be changed. An easy way to understand that is if you have a look at an objects ID.

Take List for example:

>>> b = [1, 2, 3, 4]
>>> id(b)
47490376L
>>> b[1] = 1
>>> b
[1, 1, 3, 4]
>>> id(b)
47490376L

Take Dictionary for example:

>>> aDict = {'host': 'earth', 'port': 80}
>>> id(aDict)
46236680L
>>> aDict['port'] = 90
>>> id(aDict)
46236680L

Take Integer for example:

>>> a = 1
>>> id(a)
31121592L
>>> a = 2
>>> id(a)
31121568L

Take Tuple for example:

>>> aTuple = (1, 2, 3, 4)
>>> aTuple[1] = 1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

Take String for example:

>>> aString = "For Example"
>>> aString[1] = 'U'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

你可能感兴趣的:(Mutability Vs Immutability)