我在 Python 中遇到了一个非常奇怪的行为。使用派生自 的类UserDict
,迭代a.items()
器在 for 循环中的行为不同于a.data.items()
,即使两者相同:
Python 3.3.1 (default, Apr 17 2013, 22:32:14)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datastruct import QueueDict
>>> a=QueueDict(maxsize=1700)
>>> for i in range(1000):
... a[str(i)]=1/(i+1)
...
>>> a.items()
ItemsView(OrderedDict([('991', 0.0010080645161290322), ('992', 0.0010070493454179255), ('993', 0.001006036217303823), ('994', 0.0010050251256281408), ('995', 0.001004016064257028), ('996', 0.0010030090270812437), ('997', 0.001002004008016032), ('998', 0.001001001001001001), ('999', 0.001)]))
>>> a.data.items()
ItemsView(OrderedDict([('991', 0.0010080645161290322), ('992', 0.0010070493454179255), ('993', 0.001006036217303823), ('994', 0.0010050251256281408), ('995', 0.001004016064257028), ('996', 0.0010030090270812437), ('997', 0.001002004008016032), ('998', 0.001001001001001001), ('999', 0.001)]))
>>> a.items()==a.data.items()
True
>>> # nevertheless:
...
>>> for item in a.items(): print(item)
...
('992', 0.0010070493454179255)
>>> for item in a.data.items(): print(item)
...
('993', 0.001006036217303823)
('994', 0.0010050251256281408)
('995', 0.001004016064257028)
('996', 0.0010030090270812437)
('997', 0.001002004008016032)
('998', 0.001001001001001001)
('999', 0.001)
('991', 0.0010080645161290322)
('992', 0.0010070493454179255)
>>>
类定义如下:
import collections, sys
class QueueDict(collections.UserDict):
def __init__(self, maxsize=1*((2**10)**2), *args, **kwargs ):
self._maxsize=maxsize
super().__init__(*args, **kwargs)
self.data=collections.OrderedDict(self.data)
def __getitem__(self, key):
self.data.move_to_end(key)
return super().__getitem__(key)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._purge()
def _purge(self):
while sys.getsizeof(self.data) > self._maxsize:
self.data.popitem(last=False)
这很令人不安。任何想法[通过“视觉”检查以及通过(a.items()==a.data.items()) == True
]如何相同的对象,以及为什么它在 for 循环中表现不同?
感谢您的帮助和想法!