Python 2.7中文件处理中的类

时间:2017-02-03 14:19:11

标签: python-2.7 class binaryfiles file-handling

我在交互模式下获得此输出。

 class test:
        def p(self):
            print 'PP'

>>> f=open('E:\Python\Roy Progs\Test','w')
>>> t=test()
>>> import pickle
>>> pickle.dump(t,f)
>>> f.close()
>>> f=open('E:\Python\Roy Progs\Test','r')
>>> pickle.load(f).p()
PP
>>> f.close()
>>> 
=============================== RESTART: Shell ===============================
>>> f=open('E:\Python\Roy Progs\Test','r')
>>> import pickle
>>> pickle.load(f).p()

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    pickle.load(f).p()
  File "E:\Python\lib\pickle.py", line 1384, in load
    return Unpickler(file).load()
  File "E:\Python\lib\pickle.py", line 864, in load
    dispatch[key](self)
  File "E:\Python\lib\pickle.py", line 1075, in load_inst
    klass = self.find_class(module, name)
  File "E:\Python\lib\pickle.py", line 1132, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'test'

从输出中我意识到类的定义(其对象存储在文件中)必须在检索数据和使用它时在RAM中。但是我不明白为什么会出现这种情况,通过在文件中存储对象我也不存储类定义?

1 个答案:

答案 0 :(得分:1)

pickle模块通过命名引用存储类。如果更改类的名称或位置pickle将引发错误。

可以在交互式中看到一个快速说明:

>>> class test:
    x = 5


>>> from pickle import dumps
>>> dumps(test)
'c__main__\ntest\np0\n.' # pickle is storing a reference to 'test'

要成功调用load pickle必须能够找到以前定义的类(在空闲时调用restart时会被销毁)