python:无法解释的无限递归__

2024-06-02 06:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一段代码,它进入一个无限递归循环,它只由__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__?我完全搞不懂。谢谢!在


Tags: 代码selfindexreturninitisdefthis
1条回答
网友
1楼 · 发布于 2024-06-02 06:59:36
>> mylist.index('foo')
ValueError: 'foo' is not in list

实际上,您从未将mydict添加到mylist中,因此index方法试图引发此错误。错误包含dict的repr。当然,dict的repr试图在它不在的列表中查找它的index,这引发了一个异常,它的错误消息是使用dict的repr计算的,当然,它会尝试在它不在的列表中查找它的index,并且。。。在

相关问题 更多 >