Mutable and immutable objects in python

Knowledge point: In python, everything is an object.

   There is no so-called pass-by-value call in python, everything passed is the reference of the object , which can also be considered as pass-by-reference.

1. Mutable and Immutable Objects

Objects allocated by Python in the heap are divided into two categories: mutable objects and immutable objects. The so-called mutable object means that the content of the object is changeable, while the immutable object means that the content of the object is immutable.

Immutable (immutable): int, string (string), float, (numeric number), tuple (tuple)

Mutable: dictionary, list

Immutable Type Features:

  See the example below (Example 1)

[python] view plain copy
i = 73
i += 2

As can be seen from the above figure, the characteristics of immutable objects have not changed. What has changed is that a new object is created and the object reference of the variable is changed.

  Look at an example (Example 2)

>>>x = 1
>>>y = 1
>>>x = 1
>>> x is y
True
>>>y is z
True

  As shown above, because integers are immutable, x, y, and z all point to a memory address with a value of 1 in memory, that is, x, y, and z all point to the same address. It is worth noting that, For shaping, currently only (-1,100) is supported.

  To summarize, the pros and cons of immutable objects.

    The advantage is that this reduces the memory footprint of repeated values .

    The disadvantage is that, as shown in Example 1, I want to modify the value of the variable binding. If the memory block with the value is not used in the memory, then a new memory must be opened up and the new address is bound to the variable name. Instead of modifying the value of the memory block originally pointed to by the variable, this time brings a certain reduction in execution efficiency .

  Let's look at an example of a mutable object (Example 3)

m=[5,9]
m+=[6]

Second, the function parameters:

Python function parameters For mutable objects, changes to parameters within the function will affect the original object; for immutable objects, changes to parameters within the function will not affect the original parameters. the reason is:

1. Mutable object, the parameter changed is the mutable object, and its content can be modified.

2. Immutable object, what changes is the object pointed to by the variable in the function.


Reference link:

https://blog.csdn.net/taohuaxinmu123/article/details/39008281


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325389218&siteId=291194637