如何钻一个 class 并在以后修改它?

How to dill a class and modify it later?

我目前正在为 Python 使用 dill 库,我正在使用它来制作 class。这是 class

class QQQ:
    def __init__(self, name):
        self.name = name
        self.total = 0

    def add_1(self, add):
        self.total = 1 + add
        # To test the below after loading the saved dill
        # self.total = 101 + add

    @property
    def get_total(self):
        return self.total

然后我实例化我的 class 并钻取它

import dill

path = '/path/file'
dill.settings['recurse'] = True
from x.qqq import QQQ

qqq = QQQ(name='Test1')
qqq.add_1(100)
with open(path, 'wb') as f:
    dill.dump(qqq, f)
class QQQ:
    def __init__(self, name):
        self.name = name
        self.total = 0

    def add_1(self, add):
        # self.total = 1 + add
        self.total = 101 + add

    @property
    def get_total(self):
        return self.total

虽然,如果我修改这个 QQQ class 然后我加载我的转储文件:

import dill
path = '/path/file'
dill.settings['recurse'] = True

with open(path, 'rb') as f:
    old_class = dill.load(f)

old_class.add_1(100)
total = old_class.get_total

它使用 修改后的 class 而不是我之前钻研的 class。

我是 dill 作者。它忽略了存储的 class,因为这被确定为正确的做法。如果您重新定义了 class,那么您有两个选择,使用新定义的 class... 或忽略它并使用旧的 class 定义。 dill 的旧版本忽略了新的 class 定义,但后来认为这不是正确的默认行为。默认情况下,最新版本都将遵循任何重新定义的 class。

如果您确实想忽略新的 class 定义,那么您必须在加载时执行此操作,如下所述。

>>> import dill
>>> class QQQ(object):
...     def __init__(self):    
...         self.total = 0
...     def increment(self, n=1):
...         self.total += n
... 
>>> q = QQQ() 
>>> q.increment()
>>> q.total
1
>>> dill.dump(q, open('qqq.pkl', 'wb'))
>>> 

然后重新启动您的会话。你得到新的 class 定义,除非你使用 ignore 标志。

>>> import dill
>>> class QQQ(object):
...     def __init__(self):
...         self.total = 0
...     def increment(self, n=10):
...         self.total += n
...     def decrement(self, n=10):
...         self.total -= n
... 
>>> q = dill.load(open('qqq.pkl', 'rb'))
>>> q.total
1
>>> q.increment()
>>> q.total
11
>>> p = dill.load(open('qqq.pkl', 'rb'), ignore=True)
>>> p.total
1
>>> p.increment()
>>> p.total
2