Python's memory management small understanding

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.