gpt4 book ai didi

Python 列表范围

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:17 24 4
gpt4 key购买 nike

让我们检查一下。

class SomeObject:

testList = []

def setList(self, data):
self.testList = data

def getList(self):
return self.testList

class UtilClass:

def populateList(self, foreign, str):

data = []
data.append(str)

foreign.setList(data)


def main():

data = SomeObject()
data2 = SomeObject()
util = UtilClass()

util.populateList(data, "Test 1")
util.populateList(data2, "Test 2")
util.populateList(data, "Test 3")


print(data.getList())
print(data2.getList())

if __name__=="__main__":
main()

main 中的 data 对象现在包含什么,在 populateList() 中构造的列表的副本或引用对吗?

我应该做类似 list()copy.copy()copy.deepcopy() 的事情吗?数据对象应该超出 populateList 的范围,对吧?

当我将另一个列表传递给 util 对象时会发生什么? data 中的列表是否被更改或覆盖?

如果 populateList 中的 data 超出范围,为什么在第二次调用 populateList 后它仍然有效?

最佳答案

What does the data object inside of main now contain, a copy of a the list constructed inside of populateList() or a reference to it?

对其的引用。但是由于您没有将引用传递给另一个对象。 data 是唯一引用该列表的数据。

Should I do something like list() or copy.copy() or copy.deepcopy()? The data object should go out of scope inside of populateList, right?

不,仅当您想要构建一个副本时(例如,如果您想稍后进一步更改列表)。该对象不会被垃圾回收,因为它是在堆上分配的。只要有一个事件变量引用它,它就会保持事件状态。

What happens when I pass another list to the util object? Does the list indata get altered or overwritten?

不,util 不会引用新列表,旧列表独立存在。如果没有其他对象引用旧列表,旧列表最终将被垃圾收集。

If the data inside of populateList go out of scope, why is it valid after the second call to populateList?

超出范围,程序员说列表不再监听data identifier。但这份名单仍然存在于内存中。如果其他对象引用它,他们可以更改/修改它等。

关于Python 列表范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com