python从堆创建一切? [英] python creates everything from heap?

查看:30
本文介绍了python从堆创建一切?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

in c/c++, you have variables in stack when you create a local variable inside a function.

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

CLU 对象独立于过程激活而存在.空间for 对象是从动态存储区分配的/.../中理论上,所有物体都将永远存在.在实践中,当对象不存在时,对象使用的空间可能会被回收任何 CLU 程序都不再可以访问.

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)?并且当没有与它们关联的名称时对象被释放?(如智能指针)?

Does this mean objects in python is created from heap(as in malloc in c/c++)? and the objects are deallocated when there 's no name associated with them?(like smart pointers)?

示例:

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

foo("hello")

myList = foo("bye")

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

So the first result([]) was created in the heap and got deallocated because there's no name associated with it?

推荐答案

是的,所有 Python 对象都存在于堆上(至少在 CPython 上).它们是引用计数的:当最后一次引用物体消失.(CPython 还有一个垃圾收集器来中断循环.)

Yes, all Python objects live on the heap (at least on CPython.) They are reference-counted: they are de-allocated when the last reference to the object disappear. (CPython also has a garbage collector to break cycles.)

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

In CPython your first list disappears as soon as the function returns since you did not bind the return value to a name and the reference count dropped to zero. In other implementation the object may live longer until the garbage-collector kicks in.

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

Some objects (like open files) have resources attached that are automatically freed when the object is deallocated, but because of the above it is not recommended to rely on this. Resources should be closed explicitly when you are done with them.

这篇关于python从堆创建一切?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆