我正在编写一个定义__iter__and的类__len__,其中 的值__len__取决于__iter__. 我得到了一个有趣的RecursionError.
语言版本:Python 3.8.6、3.7.6。 示例仅用于说明错误。
在以下示例中,Iter.__len__()尝试解包self,将结果存储在 a 中list,然后尝试调用该list.__len__()列表上的内置函数以获取长度。
>>> class Iter:
... def __iter__(self):
... return range(5).__iter__()
... def __len__(self):
... return list.__len__([*self])
...
>>> len(Iter())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __len__
File "<stdin>", line 5, in __len__
File "<stdin>", line 5, in __len__
[Previous line repeated 993 more times] …Run Code Online (Sandbox Code Playgroud)