python:无法解释的无限递归与__repr__

Bor*_*kov 3 python debugging recursion repr

这是一段代码,它进入一个无限递归循环,它只包含__repr__函数,似乎在调用自身.但我真的看不到它是怎么称呼它自己的.而且,我甚至无法理解,它是如何被称为:

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 :(
Run Code Online (Sandbox Code Playgroud)

执行此代码会导致:

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
Run Code Online (Sandbox Code Playgroud)

你明白了,怎么str(mylist.index(mydict))设法打电话__repr__?我完全不解.谢谢!

kwa*_*ord 5

>> mylist.index('foo')
ValueError: 'foo' is not in list
Run Code Online (Sandbox Code Playgroud)

你从未真正将mydict添加到mylist,因此该index方法试图引发此错误.该错误包含dict的repr.当然,dict的repr试图index在它不在的列表中查找它,这引发了一个异常,其错误消息是使用dict的repr计算的,当然,它试图查找它index在列表中它不在,并且......