3

__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__か? 私は完全に困惑しています。ありがとう!

4

1 に答える 1

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

実際には mydict を mylist に追加していないため、indexメソッドはこのエラーを発生させようとします。エラーには、dict の repr が含まれています。もちろん、dictのreprはindexリストにないものを検索しようとします。これにより例外が発生し、そのエラーメッセージはdictのreprを使用して計算され、もちろん検索を試みますそれindexが入っていないリストにあり、そして...

于 2014-03-25T15:05:03.000 に答える