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).
您可以检查
id
:这表明每个循环都在创建
k
。你知道吗每次迭代中被创建和丢弃的对象都是
int
,这个过程不受在循环前命名某物k
的影响。我还认为对象/名称k
在第一次迭代中被创建一次,然后在随后的迭代中被重新分配-在迭代过程中它不会被丢弃。你知道吗Python has names not variables
Facts and myths about Python names and values
是的,每次迭代都会创建一个新对象。至于删除,则是具体实施的。例如,CPython使用引用计数,当
k
到达循环体的末尾时将删除它。在其他实现中,垃圾收集器可以批量清除这些对象。见docs:相关问题 更多 >
编程相关推荐