如何在Python中使用pickle创建持久性类 [英] How to create a persistant class using pickle in Python

查看:98
本文介绍了如何在Python中使用pickle创建持久性类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的新手... 我有下面的类Key,它扩展了dict:

New to python... I have the following class Key, that extends dict:

class Key( dict ):

    def __init__( self ):
        self = { some dictionary stuff... }

    def __getstate__(self):
        state = self.__dict__.copy()
        return state

    def __setstate__(self, state):
        self.__dict__.update( state )

我想使用pickle.dump保存类的实例及其数据,然后使用pickle.load检索数据.我知道我应该以某种方式更改getstate和setstate,但是,我对如何做到这一点尚不完全清楚……任何帮助将不胜感激!

I want to save an instance of the class with its data using pickle.dump and then retrieve the data using pickle.load. I understand that I am supposed to somehow change the getstate and the setstate, however, am not entirely clear on how I am supposed to do that... any help would be greatly appreciated!

推荐答案

我写了一个dict的子类,就是在这里做的.

I wrote a subclass of dict that does this here it is.

class AttrDict(dict):
    """A dictionary with attribute-style access. It maps attribute access to
    the real dictionary.  """
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)

    def __getstate__(self):
        return self.__dict__.items()

    def __setstate__(self, items):
        for key, val in items:
            self.__dict__[key] = val

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))

    def __setitem__(self, key, value):
        return super(AttrDict, self).__setitem__(key, value)

    def __getitem__(self, name):
        return super(AttrDict, self).__getitem__(name)

    def __delitem__(self, name):
        return super(AttrDict, self).__delitem__(name)

    __getattr__ = __getitem__
    __setattr__ = __setitem__

    def copy(self):
        return AttrDict(self)

它基本上将状态转换为基本元组,然后再将其带回去.

It basically converts the state to a basic tuple, and takes that back again to unpickle.

但是请注意,您必须必须对原始源文件进行修补.酸洗实际上并不保存类本身,而仅保存实例状态. Python将需要原始的类定义来重新创建.

But be aware that you have to have to original source file available to unpickle. The pickling does not actually save the class itself, only the instance state. Python will need the original class definition to re-create from.

这篇关于如何在Python中使用pickle创建持久性类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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