下面是一段代码,它进入一个无限递归循环,它只由__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 :(
执行此代码会导致:
^{pr2}$你明白吗,str(mylist.index(mydict))
是如何成功地调用了__repr__
?我完全搞不懂。谢谢!在
实际上,您从未将mydict添加到mylist中,因此
index
方法试图引发此错误。错误包含dict的repr。当然,dict的repr试图在它不在的列表中查找它的index
,这引发了一个异常,它的错误消息是使用dict的repr计算的,当然,它会尝试在它不在的列表中查找它的index
,并且。。。在相关问题 更多 >
编程相关推荐