python:带_repr的无法解释的无限递归__
下面是一段代码,它进入了一个无限递归循环,它只包含python:带_repr的无法解释的无限递归__,python,debugging,recursion,repr,Python,Debugging,Recursion,Repr,下面是一段代码,它进入了一个无限递归循环,它只包含\uuuu repr\uuu函数,似乎在调用自己。但我真的不明白它是怎么称呼自己的。而且,我甚至不明白它是怎么叫的: class MyList(list): #this is storage for MyDict objects def __init__(self): super(MyList, self).__init__() class MyDict(dict): def __init__(self, myl
\uuuu repr\uuu
函数,似乎在调用自己。但我真的不明白它是怎么称呼自己的。而且,我甚至不明白它是怎么叫的:
class MyList(list): #this is storage for MyDict objects
def __init__(self):
super(MyList, self).__init__()
class MyDict(dict):
def __init__(self, mylist):
self.mylist = mylist #mydict remembers mylist, to which it belongs
def __hash__(self):
return id(self)
def __eq__(self, other):
return self is other
def __repr__(self):
return str(self.mylist.index(self)) #!!!this is the crazy repr, going into recursion
def __str__(self):
return str(self.__repr__())
mylist = MyList()
mydict = MyDict(mylist)
mydict.update({1:2})
print str(mylist.index(mydict)) #here we die :(
执行此代码会导致:
Traceback (most recent call last):
File "test_analogue.py", line 20, in <module>
print str(mylist.index(mydict))
File "test_analogue.py", line 13, in __repr__
return str(self.mylist.index(self))
File "test_analogue.py", line 13, in __repr__
...
... (repetition of last 2 lines for ~666 times)
...
File "test_analogue.py", line 13, in __repr__
return str(self.mylist.index(self))
RuntimeError: maximum recursion depth exceeded while calling a Python object
回溯(最近一次呼叫最后一次):
文件“test_simulator.py”,第20行,in
打印str(mylist.index(mydict))
文件“test_simulation.py”,第13行,在报告中__
返回str(self.mylist.index(self))
文件“test_simulation.py”,第13行,在报告中__
...
... (重复最后两行约666次)
...
文件“test_simulation.py”,第13行,在报告中__
返回str(self.mylist.index(self))
RuntimeError:调用Python对象时超出了最大递归深度
你知道,str(mylist.index(mydict))
是如何调用\uuuu repr\uuu
的吗?我完全迷惑不解。谢谢
>> mylist.index('foo')
ValueError: 'foo' is not in list
您从未将mydict实际添加到mylist,因此
index
方法试图引发此错误。错误包含dict的repr。当然,dict的repr会尝试在其不在的列表中查找其索引
,这会引发异常,其错误消息是使用dict的repr计算的,该repr会尝试在其不在的列表中查找其索引
,和…\uuuuu repr\uuuuu
函数定义覆盖默认的\uuuuuu repr\uuuuu
,该函数由str(mylist.index(mydict))
调用。注释掉你的\uuuu repr\uuuu
函数,然后查看@对不起,我看不出,str(mylist.index(mydict))
调用\uuuu repr\uuu
的确切方式mylist.index(mydict)
应返回int
,并且int
应通过str()
转换为str
。\uuuu repr\uuuu
在哪里?问题在于引发的异常,因为mydict
不在mylist
中。例外情况试图得到这条命令的报告。@kwatford Man,你说得对。如果我对这样的事情目瞪口呆的话,我最好去度假。谢谢大家。