Python内存分配

时间:2018-11-26 23:49:15

标签: python pointers memory

我真的很感兴趣Python内存分配的工作方式。

我写了两段代码:

1。

list = []
a = [1,2,3]
list.append(a)
a = [3,2,1]
print(list)
print(a)

2。

def change(list):
    list[1] = 50
    list[2] = 70

list = []
a = [1,2,3]
list.append(a)
change(a)
print(list)
print(a)

当我编译第一个代码时,我得到结果[[1,2,3]]和[3,2,1]。

但是,当我编译第二个代码时,我得到的结果是[1,50,70]。

在第一种情况下,我创建一个对象“ a”和一个数组“ list”。当我将对象“ a”附加到数组时,数组实际上指向它。然后,当我分配“ a”新数组[3,2,1]时,对象[1,2,3]保存在数组中,“ a”指向新数组[3,2,1]。 / p>

在第二种情况下,我还创建了一个对象“ a”和一个数组“ list”。我将“ a”附加到数组上,还有一个指针指向“ a”。然后,我在数组“ a”上调用方法。调用函数并更改元素的值后,数组“列表”仍指向对象“ a”,而无需创建新实例。

有人可以向我解释一下它的真正作用方式吗?

1 个答案:

答案 0 :(得分:3)

您在Python中创建的每个变量都是对对象的引用。列表是包含对不同对象的多个引用的对象。

几乎所有python操作都会修改这些引用,而不是对象。因此,当您执行list[1] = 50时,您正在修改列表项包含的第二个引用。

我发现Python Tutor

是用于可视化此功能的有用工具。

第一个例子

list = [] # you create a reference from `list` to the the new list object you have created
a = [1,2,3] # you create a reference from `a` to the new list you have created which itself contains 3 references to three objects, `1`, `2` and `3`.
list.append(a) # this adds another reference to `list` to the object referenced by `a` which is the object `[1, 2, 3]`
a = [3,2,1] # create a reference from `a` to the new list you have created which itself contains 3 references to three objects, `3`, `2` and `1`.
print(list) # print the object referenced by `list`
print(a) # print the object referenced by `a`

第二个例子

def change(list): # create a reference from `change` to a function object
    list[1] = 50 #change the second reference in the object referenced by `list` to `50`
    list[2] = 70 #change the third reference in the object referenced by `list` to `70`

list = [] # create a reference from `list` to a new list object
a = [1,2,3] # create a reference from `a` to a new list object which itself contains three references to three objects, `1`, `2` and `3`.
list.append(a) # add a reference to list to the object pointed to by `a`
change(a) # call the function referenced by change
print(list) # print the object referenced by `list`
print(a) # print the object referenced by `a`
相关问题