访问字典VS访问货架 [英] Accessing Dictionaries VS Accessing Shelves

查看:118
本文介绍了访问字典VS访问货架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个字典,其中有一个数字作为键,一个Class作为一个值。我可以像这样访问该类的属性:

Currently, I have a dictionary that has a number as the key and a Class as a value. I can access the attributes of that Class like so:

dictionary[str(instantiated_class_id_number)].attribute1

由于内存问题,我想使用 shelve 模块。我想知道如果这样做是合理的。搁置字典是否与标准字典完全相同?如果不是,它有什么不同?

Due to memory issues, I want to use the shelve module. I am wondering if doing so is plausible. Does a shelve dictionary act the exact same as a standard dictionary? If not, how does it differ?

推荐答案

Shelve的行为与字典没有完全相同的行为,特别是当修改已经在字典中。

Shelve doesn't act extactly the same as dictionary, notably when modifying objects that are already in the dictionary.

区别在于,当您将一个类添加到字典中时,存储引用,但是shelve保留对象的酸洗(序列化)副本。如果然后修改对象,您将
修改内存中的副本,而不是腌制版本。这可以通过 shelf.sync() shelf.close()
写出条目。做所有这些工作确实需要跟踪还没有被回写的所有检索到的对象,所以你必须调用shelf.sync()来清除缓存。

The difference is that when you add a class to a dictionary a reference is stored, but shelve keeps a pickled (serialized) copy of the object. If you then modify the object you will modify the in-memory copy, but not the pickled version. That can be handled (mostly) transparently by shelf.sync() and shelf.close(), which write out entries. Making all that work does require tracking all retrieved objects which haven't been written back yet so you do have to call shelf.sync() to clear the cache.

shelf.sync()清除缓存的问题是您可以保留对该对象的引用并再次修改。

The problem with shelf.sync() clearing the cache is that you can keep a reference to the object and modify it again.

此代码不符合预期的架子,但可以使用字典:

This code doesn't work as expected with a shelf, but will work with a dictionary:

s["foo"] = MyClass()
s["foo"].X = 8 
p = s["foo"] # store a reference to the object
p.X = 9 # update the reference
s.sync() # flushes the cache
p.X = 0
print "value in memory: %d" % p.X # prints 0
print "value in shelf: %d" % s["foo"].X # prints 9

同步刷新缓存,以便修改'p'对象从缓存中丢失,因此不会写回。

Sync flushes the cache so the modified 'p' object is lost from the cache so it isn't written back.

这篇关于访问字典VS访问货架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆