gpt4 book ai didi

Python 作用域/对象生命

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:45 25 4
gpt4 key购买 nike

在这段代码中,存储k 的对象是否在循环中的每次迭代中被创建和删除?我认为是的,所以我通常在循环之上声明任何此类变量。

while (1):
k = randint(0,10)

最佳答案

是的,每次迭代都会创建一个新对象。至于删除,它是特定于实现的。例如,CPython 使用引用计数,并在 k 到达循环体末尾时将其删除。在其他实现中,这些对象可以由垃圾收集器分批清除。参见 docs :

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files).

关于Python 作用域/对象生命,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28934914/

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