问题描述
以下代码陷入无限循环:
The following code runs into an infinite loop:
class SubCommandMap:
def __init__(self):
self._command = dict()
def __getitem__(self, key):
return self._command.get(key)
def __setitem__(self, key, value):
self._command[key] = value
m = SubCommandMap()
" " in m # <- why is this an infinite loop?
当然这是一个错误.假定 m
是不同类型的不同对象.但是,为什么这会导致无限循环而不是引发异常?
Of course this is an error. m
was suppossed to be a different object of a different type.But why does this end up in an infinite loop instead of throwing an exception?
我添加了以下方法:
def __contains__(self, other):
raise NotImplementedError()
现在我收到一条适当的错误消息.
Now I am getting an appropriate error message.
在其他类似情况下,我需要注意避免无限循环吗?
Are there other, similar cases where I need to be careful to avoid an infinite loop?
推荐答案
在缺少 __ contains __
的情况下, in
运算符将使用 __ getitem __
您定义的方法来查看它是否获取您要查找的对象.它将依次将每个int传递给 __ getitem __
,直到找到该项或该方法引发异常.如果这些都不发生,那么您将陷入无限循环.
In the absence of __contains__
the in
operator will use the __getitem__
method you have defined to see if it gets the object you're looking for. It will pass every int in turn to __getitem__
until it finds the item or the method raises an exception. If neither of those happens, you have an infinite loop.
这篇关于为什么我会在没有__contains__的情况下陷入无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!