0
我試了一下在這裏推薦https://stackoverflow.com/a/41112823/5618523但我仍然有問題這是爲什麼導致遞歸錯誤
class AppendiveDict(c.OrderedDict):
def __init__(self,func,*args):
self.func = func
c.OrderedDict.__init__(self,args)
def __setitem__(self, key, value,):
if key in self:
self[key] = self.func(self[key])
else:
c.OrderedDict.__setitem__(self,key,value)
a = AppendiveDict((lambda y: y + "sdf"),("a","b"),("c","d"),("e","f"),("a","b"))
a
此類的一點是,它是假設在字典的時候就已經申請項的功能它會重現這個項目。
RecursionError Traceback (most recent call last)
<ipython-input-15-b4bd349c86bf> in <module>()
11 else:
12 c.OrderedDict.__setitem__(self,key,value)
---> 13 a = AppendiveDict((lambda y: y + "sdf"),("a","b"),("c","d"),("e","f"),("a","b"))
14 a
<ipython-input-15-b4bd349c86bf> in __init__(self, func, *args)
5 def __init__(self,func,*args):
6 self.func = func
----> 7 c.OrderedDict.__init__(self,args)
8 def __setitem__(self, key, value,):
9 if key in self:
<ipython-input-15-b4bd349c86bf> in __setitem__(self, key, value)
8 def __setitem__(self, key, value,):
9 if key in self:
---> 10 self[key] = self.func(self[key])
11 else:
12 c.OrderedDict.__setitem__(self,key,value)
數3只是重複 。如果我c.OrderedDict後放self.func。 init(self,args)它會導致屬性錯誤,說self.func不存在。
'self [key] = xxx'調用無限遞歸的'self .__ setitem __(key,xxx)'。 – thebjorn