Thu*_*nix 5 python iterator python-3.x
我希望看到该类的定义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
Run Code Online (Sandbox Code Playgroud)
我很确定对象it具有对该对象的引用l。这个例子证明了这一点:
import sys
l = [1,2,3,4]
print(sys.getrefcount(l)) # prints 2
it = iter(l)
print(sys.getrefcount(l)) # prints 3
Run Code Online (Sandbox Code Playgroud)
因此,第三参考肯定来自 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
Run Code Online (Sandbox Code Playgroud)
编辑:应该注意的是,当耗尽并引发l时,对的引用就会消失。因此,当您完成迭代 时,上面的引用检查将失败。根据您的用例,这可能是一个功能或错误,但您应该意识到这一点。itStopIterationit
# 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |