如何序列化哈希对象?我正在使用搁置来存储大量对象。
层次:
- user
- client
- friend
user.py:
import time
import hashlib
from localfile import localfile
class user(object):
_id = 0
_ip = "127.0.0.1"
_nick = "Unnamed"
_files = {}
def __init__(self, ip="127.0.0.1", nick="Unnamed"):
self._id = hashlib.sha1(str(time.time()))
self._ip = ip
self._nick = nick
def add_file(self, localfile):
self._files[localfile.hash] = localfile
def delete_file(self, localfile):
del self._files[localfile.hash]
if __name__ == "__main__":
pass
client.py:
from user import user
from friend import friend
class client(user):
_friends = []
def __init__(self, ip="127.0.0.1", nick="Unnamed"):
user.__init__(self, ip, nick)
@property
def friends(self):
return self._friends
@friends.setter
def friends(self, value):
self._friends = value
def add_friend(self, client):
self._friends.append(client)
def delete_friend(self, client):
self._friends.remove(client)
if __name__ == "__main__":
import shelve
x = shelve.open("localfile", 'c')
cliente = client()
cliente.add_friend(friend("127.0.0.1", "Amigo1"))
cliente.add_friend(friend("127.0.0.1", "Amigo2"))
x["client"] = cliente
print x["client"].friends
x.close()
错误:
facon@facon-E1210:~/Documentos/workspace/test$ python client.py
Traceback (most recent call last):
File "client.py", line 28, in <module>
x["client"] = cliente
File "/usr/lib/python2.7/shelve.py", line 132, in __setitem__
p.dump(value)
File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle HASH objects
EDITED
添加了user.py。
答案 0 :(得分:4)
由于您无法使用HASH
序列化shelve
个对象,因此您必须以不同的方式提供相同的信息。例如,您只能保存哈希的摘要。
答案 1 :(得分:0)
cliente
中的某些内容,client
类的实例,不可修改。
这是list of those types which are picklable。
您发布的代码未显示cliente
包含哪些不可选择的内容。但您可以通过删除不可取消的属性(如果不需要)或定义__getstate__
和__setstate
以使client
可选择来解决问题。