簡體   English   中英

python:無法解釋的無限遞歸與__repr__

[英]python: unexplainable infinite recursion with __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 :(

執行此代碼會導致:

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

你明白, str(mylist.index(mydict))設法調用__repr__ 我完全不解。 謝謝!

>> mylist.index('foo')
ValueError: 'foo' is not in list

您實際上從未將mydict添加到mylist,因此index方法會嘗試引發此錯誤。 該錯誤包含dict的repr。 當然,dict的repr試圖在它不在的列表中查找它的index ,這引發了一個異常,其錯誤消息是使用dict的repr計算的,當然,這會嘗試查看列表中的index不在其中,並且......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM