从超级类中挑选一个子类

时间:2014-08-21 21:54:23

标签: python pickle

我已经做了一些挖掘,我发现了一些线索,但我发现它们有点难以理解,所以我会爱一点帮助。我想做的是如下

class A(object):

    def do_stuff(self):
        self.step1()
        #Want to save states of B and C here
        self.save()
        self.step2()
        self.step3()

    # HERE is where I need help
    def save(self):
         f = open("store_here.file", "w")
         pickle.dump(self, f)

class B(A):
     # Has own step1(), step2(), and step3() methods
class C(A):
     # Has own step1(), step2(), and step3() methods

我希望在保存的步骤中保存B类和C类的实例,以便稍后加载它们,然后跳过step1()。我得到以下错误“无法腌制文件对象”,这没有用。

1 个答案:

答案 0 :(得分:0)

如果我使用dill,它可以序列化python中的大多数东西,我不会收到错误。 (您可以在此处找到dillhttps://github.com/uqfoundation

我假设你想做这样的事......

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> 
>>> class A(object):
...   def step1(self):
...     self.x = []     
...   def step2(self):
...     self.x.append(1)
...   def step3(self):
...     self.x.append(2)
...     print 'woohoo!'
...   def do_stuff(self):
...     self.step1()
...     self.save()
...     self.step2()
...     self.step3()
...   def save(self):
...     f = open('foo.pkl', "w")
...     dill.dump(self, f)
...   
>>> a = A()
>>> a.do_stuff()
woohoo!

现在建立B级......

>>> class B(A):
...   def step1(self):
...     self.x = {}
...   def step2(self):
...     self.x['a'] = 1
...   def step3(self):
...     self.x['b'] = 2
...     print 'hoowoo!'
... 
>>> _a = dill.load(open('foo.pkl'))    
>>> _a.x
[]
>>> b = B()
>>> b.do_stuff()
hoowoo!
>>> _b = dill.load(open('foo.pkl'))
>>> _b
<__main__.B object at 0x110c16050>
>>> _a
<__main__.A object at 0x110c04a10>
>>> _b.x
{}
>>> 

注意,我不是将文件存储为属性,而是在任何地方。不要那样做。你可能比我在上面更聪明,并且有一个属性来传递文件名或类似的东西。