gpt4 book ai didi

python - list_iterator 类在哪里定义?

转载 作者:行者123 更新时间:2023-12-04 19:25:19 27 4
gpt4 key购买 nike

我想看看类的定义list_iterator .当我尝试使用函数 help 显示其定义时我得到一个错误。有没有我必须导入的模块才能获得它的帮助?

更准确地说,我想知道如何获取对迭代器迭代的对象的引用。例如:

l = [1,2,3,4,5]
it = iter(l)
print(type(it)) # this prints: list_iterator
# how to get a reference to l using it

我很确定对象 it引用了对象 l .这个例子证明了这一点:
import sys
l = [1,2,3,4]
print(sys.getrefcount(l)) # prints 2
it = iter(l)
print(sys.getrefcount(l)) # prints 3

所以第三个引用肯定来自 it

最佳答案

垃圾回收的 get_referents 为你而做?

import gc

l = [1,2,3,4,5]
it = iter(l)

refs = gc.get_referents(it) # looks like: [[1, 2, 3, 4, 5]]
assert l in refs # True
assert l == refs[0] # True

编辑:应该注意的是对 l 的引用当 it 时消失筋疲力尽并提出 StopIteration .因此,当您完成对 it 的迭代时,上面的引用检查失败。根据您的用例,这可能是一个功能或错误,但您应该意识到这一点。
# Exhaust the iterator
for x in it:
pass

refs = gc.get_referents(it)
assert l not in refs # No more reference to l
assert not refs # No more reference to anything actually

关于python - list_iterator 类在哪里定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58963507/

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