gpt4 book ai didi

python 从堆中创建一切?

转载 作者:太空狗 更新时间:2023-10-29 21:15:38 25 4
gpt4 key购买 nike

在 c/c++ 中,当您在函数内创建局部变量时,变量在堆栈中。

http://effbot.org/zone/call-by-object.htm

CLU objects exist independently of procedure activations. Space for objects is allocated from a dynamic storage area /.../ In theory, all objects continue to exist forever. In practice, the space used by an object may be reclaimed when the object isno longer accessible to any CLU program.

这是否意味着 python 中的对象是从堆中创建的(如 c/c++ 中的 malloc)?对象在没有关联名称时被释放?(如智能指针)?

例子:

def foo(a): 
result = []
result.append(a)
return result

foo("hello")

myList = foo("bye")

那么第一个结果 ([]) 是在堆中创建的,并且因为没有与之关联的名称而被释放?

最佳答案

是的,所有 Python 对象都存在于堆中(至少在 CPython 中是这样)。它们是引用计数的:当对对象的最后一个引用消失时,它们将被释放。 (CPython 也有一个垃圾收集器来打破循环。)

在 CPython 中,一旦函数返回,您的第一个列表就会消失,因为您没有将返回值绑定(bind)到名称并且引用计数降为零。在其他实现中,对象可能会存活更长时间,直到垃圾收集器启动。

一些对象(如打开的文件)有附加的资源,当对象被释放时,这些资源会自动释放,但由于上述原因,不建议依赖它。资源应该在您用完后明确关闭。

关于python 从堆中创建一切?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11688647/

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