小编use*_*686的帖子

如何pickle继承自A的类B(具有许多变量)的对象,该对象定义了 __setstate__ 和 __getstate__

我的问题是:

class A(object):
    def __init__(self):
        #init
    def __setstate__(self,state):
        #A __setstate__ code here            
    def __getstate__(self):
        #A __getstate__ code here
        return state

class B(A):
    def __init__(self):
        #creates many object variables here
Run Code Online (Sandbox Code Playgroud)

A 来自外部库。

硬解

我想避免这种情况

当 pickle B 时,pickle 当然使用 A 类的__setstate__方法__getstate__,所以为了让 pickle 工作,我应该这样做:

class B(A):
    def __init__(self):
        #creates many object variables here

    def __setstate__(self,state)
        A.__setstate__(self,state)
        #B __setstate__ code here
        #getting various variables from state for example
        self._a0 = state['a0']
        self._a1 = state['a1']
        #...
        self._a100 = state['a100']
        self._a101 …
Run Code Online (Sandbox Code Playgroud)

python inheritance pickle

5
推荐指数
1
解决办法
4485
查看次数

标签 统计

inheritance ×1

pickle ×1

python ×1