from collections import OrderedDict
import unittest
class LastUpdatedOrderedDict(OrderedDict):
def __init__(self, capacity):
super(LastUpdatedOrderedDict, self).__init__()
self._capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
# print(self)
if len(self) - containsKey >= self._capacity:
last = self.popitem(last=False)
print('remove:', last)
if containsKey:
del self[key]
print('set:', (key, value))
else:
print('add:', (key, value))
OrderedDict.__setitem__(self, key, value)
问题:
del self[key] 有什么特殊用意么,如果key存在的话,直接让它执行OrderedDict.__setitem__()就行了吧,没必要del再重新self[key] = value吧
ps:这是在别人的代码里看到的,欢迎大家指教。
Look at the naming of the class. The function of this class should be to ensure that the key-value pair written in the last call is at the end. If you don't del, you just update. When printing, the key-value pair is at the front.
a is an instantiated object with 3 key-value pairs inserted respectively, see
1) 3 -> 4
2) 5 -> 6
3) 3 -> 2
among them 1) and 3) The keys are the same, but the values are different. The class means who writes the data later. When arranging, who is behind. When completing step 2), the object is LastUpdatedOrderedDict([(3, 4), (5, 6)])
When performing step 3, because your dictionary is an ordered dictionary and the key-value pair to be inserted later is at the back, the expected result is LastUpdatedOrderedDict([(5, 6), (3, 2 )]).
If you don’t delete the key here, only the original array will be updated during __setitem__, and the result will be
LastUpdatedOrderedDict([(3, 2), (5, 6)])
So you need to delete the key and disrupt it In the previous structure, key-value pairs are inserted.