1

ハッシュ オブジェクトをシリアル化するにはどうすればよいですか?、私はshelveを使用して多くのオブジェクトを格納しています。

階層:

- user
    - client
    - friend

ユーザー.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

編集済み

user.py を追加しました。

4

2 に答える 2

4

HASHではオブジェクトをシリアル化できないshelveため、同じ情報を別の方法で提供する必要があります。たとえば、ハッシュのダイジェストのみを保存できます。

于 2012-01-22T17:56:28.430 に答える
0

クラスclienteのインスタンスである内の何かがピクル可能ではありません。これは picklable である型clientのリストです。

あなたが投稿したコードは、ピクルス化できないものclienteが含まれていることを示していません。しかし、この問題は、不要な場合は unpicklable 属性を削除するか、 and を定義して picklable にすることで解決__getstate__でき__setstateますclient

于 2012-01-22T16:50:52.217 に答える