Take a look at the following section of code:
| 1234567891011121314151617 |
origin = {‘a‘:100,‘b‘:[1,2,34,5]}obj_copy ={};print origin;obj_copy[‘key1‘]= origin;obj_copy[‘key2‘]= origin;print(obj_copy)print(‘我们试图改变obj_copy中某个Key值的内容‘)obj_copy[‘key1‘][‘a‘] = 10000print(obj_copy)obj_copy[‘key1‘][‘b‘] = "hello"print(obj_copy)print(‘----------------------‘)obj_copy[‘key1‘]={‘a‘:100,‘b‘:[1,3,4,56,3]}print(obj_copy) print(origin)#输出结果发生了改变 |
Let's talk about the meaning of this piece of code:
We first given a dictionary origin = {' A ': ', ' B ': [1,2,34,5]}
We want to get a copy of this Dictionary object in order to not change the object's properties while manipulating the object. Because of the reference mechanism of the Python object, we know that when assigning an object to a variable, it is actually creating a reference to the object. As shown in the code, this is the most basic Python memory management mechanism.
So we get the output from the previous segment of the Code:
| 1234567 |
{‘a‘: 100, ‘b‘: [1, 2, 34, 5]}{‘key2‘: {‘a‘: 100, ‘b‘: [1, 2, 34, 5]}, ‘key1‘: {‘a‘: 100, ‘b‘: [1, 2, 34, 5]}}{‘key2‘: {‘a‘: 10000, ‘b‘: [1, 2, 34, 5]}, ‘key1‘: {‘a‘: 10000, ‘b‘: [1, 2, 34, 5]}}{‘key2‘: {‘a‘: 10000, ‘b‘: ‘hello‘}, ‘key1‘: {‘a‘: 10000, ‘b‘: ‘hello‘}}----------------------{‘key2‘: {‘a‘: 10000, ‘b‘: ‘hello‘}, ‘key1‘: {‘a‘: 100, ‘b‘: [1, 3, 4, 56, 3]}}{‘a‘: 1000, ‘b‘: [1, 2, 34, 5]} |
In fact, this change is the same in JavaScript.
| 12345678910111213141516 |
<script> obj = {}; obj.a = [21,2,3,4,5,67,8] obj.b = {‘key1‘:10,‘key2‘:20,‘key3‘:"hello,world"} globalValue={}; globalValue.value1 = obj; globalValue.value2 = obj; globalValue.value1=[1,2,34,5,78] alert(‘test‘)</script><body></body> |
We can also do this in this way.
Before reading this article, you can read Vamei's basic knowledge of memory management (although it may be due to a version problem, a little error)
Python's memory management small understanding