我尝试了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
这个类的意思是假设在重新计算项目时为dict中的项目应用函数。
1
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
2
<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:
3
<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。 init (self,args)之后放了self.func,它会导致属性错误,说self.func不存在。
答案 0 :(得分:2)
因为self[key]
再次调用__setitem__
,您可以尝试:
def __setitem__(self, key, value,):
if key in self:
c.OrderedDict.__setitem__(self, key, self.func(value))
编辑: 虽然重新阅读,但您打算修改当前的设定值:
def __setitem__(self, key, value):
if key in self:
c.OrderedDict.__setitem__(self, key, self.func(self[key]))
也是有效的,如果这就是你所追求的。