Python范围/对象

2024-04-19 02:29:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个代码中,存储k的对象是否在循环的每次迭代中都被创建和删除?我认为是这样,所以我通常在循环上面声明任何这样的变量。你知道吗

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

Tags: 对象代码声明randintwhile
3条回答

您可以检查id

>>> while True:
...     k = randint(1, 100)
...     print id(k)
...     time.sleep(1)
... 
140348572606072
140348572604112
140348572604600
140348572604912
^C
>>> 

这表明每个循环都在创建k。你知道吗

每次迭代中被创建和丢弃的对象都是int,这个过程不受在循环前命名某物k的影响。我还认为对象/名称k在第一次迭代中被创建一次,然后在随后的迭代中被重新分配-在迭代过程中它不会被丢弃。你知道吗

Python has names not variables

Facts and myths about Python names and values

是的,每次迭代都会创建一个新对象。至于删除,则是具体实施的。例如,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).

相关问题 更多 >