【问题标题】:Python memory allocationPython内存分配
【发布时间】:2019-04-28 16:03:21
【问题描述】:

我真的很感兴趣 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]。

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

有人能解释一下它的真正工作原理吗?

【问题讨论】:

  • 内存分配真的不是你现在应该考虑的问题。首先阅读how variables and objects interact。内存分配是一个实现细节。
  • 你能澄清一下你到底不明白什么吗?如果我理解正确,您已经描述了它是如何工作的。
  • 那些不是数组,它们是list 对象。但无论如何,请阅读以下内容:nedbatchelder.com/text/names.html

标签: python pointers memory


【解决方案1】:

您在 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`

【讨论】:

  • Python 导师值得点赞!不错的工具,真的:-)
猜你喜欢
  • 2012-12-16
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多