gpt4 book ai didi

python - 使用自定义 __getitem__ 方法解包的参数永远不会终止

转载 作者:行者123 更新时间:2023-12-04 16:23:45 26 4
gpt4 key购买 nike

有人能解释一下幕后发生了什么以及为什么这个程序没有完成吗?

class A:
def __getitem__(self, key):
return 1

print(*A())

最佳答案

这个程序没有完成,因为你定义的类是可迭代的,使用旧的序列迭代协议(protocol)。基本上,__getitem__调用整数从 0, ..., n 直到 IndexError被提出。

>>> class A:
... def __getitem__(self, key):
... return 1
...
>>> it = iter(A())
>>> next(it)
1
>>> next(it)
1
>>> next(it)
1
>>> next(it)
1
您正在解压一个无限迭代器,因此最终您将耗尽内存。
来自 iter 文档:

Without a second argument, object must be a collection object whichsupports the iteration protocol (the __iter__() method), or it mustsupport the sequence protocol (the __getitem__() method with integerarguments starting at 0). If it does not support either of thoseprotocols, TypeError is raised.

关于python - 使用自定义 __getitem__ 方法解包的参数永远不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69247270/

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