这里有一段代码,进入了一个无限递归循环,只包含一个 __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 :(
执行此代码的结果为:
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
您能理解如何调用__repr__
的str(mylist.index(mydict))
吗?我完全被困惑了。谢谢!
__repr__
函数覆盖了默认的str(mylist.index(mydict))
调用的__repr__
。注释掉你的__repr__
函数,然后看看!!! - DOOMstr(mylist.index(mydict))
如何调用__repr__
。mylist.index(mydict)
应该返回一个int
,而int
应该通过str(<int>)
转换为str
。这里的__repr__
在哪里? - Boris Burkovmydict
不在mylist
中。该异常试图获取字典的 repr。 - kwatford