gpt4 book ai didi

python - Python 中的 MemoryView 和垃圾收集

转载 作者:行者123 更新时间:2023-11-30 21:57:47 25 4
gpt4 key购买 nike

基本上:

如果我在某处声明一个字节数组:

arr = bytearray(somestr)

然后创建它的内存 View :

view = memoryview(arr)

我能否确定只要我在某处引用了 View 对象,字节数组就会保留下来?

即:

def foo():
arr = bytearray("hello world")
return memoryview(arr)

view = foo()

垃圾收集会删除原始字节数组吗?或者说这可以作为引用吗?

最佳答案

可以作为引用。 但是您可以调用release()在 View 上删除该引用:

>>> class A(bytes):
... def __del__(self):print('called')
...
>>> a =A()
>>> m = memoryview(a)
>>> del a
>>> m
<memory at 0x7fddcb00a288>
>>> len(m)
0
>>> m.release()
called

请注意,您可以使用obj attribute从 View 访问底层对象。 .

一般来说,任何未明确描述为 weak reference 的内容拥有实际引用。在内存管理语言中,这是默认设置。

关于python - Python 中的 MemoryView 和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149011/

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