【问题标题】:Classes in File Handling in Python 2.7Python 2.7 中的文件处理类
【发布时间】:2017-02-03 14:19:10
【问题描述】:

我在交互模式下得到这个输出。

 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 中。但是,我不明白为什么必须这样,通过将对象存储在文件中,我是否也没有存储类定义?

【问题讨论】:

  • 不要粘贴文本图像 - 粘贴文本本身。
  • 感谢您的建议。我希望现在可以了。

标签: python-2.7 class binaryfiles file-handling


【解决方案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必须能够找到之前定义的类(在idle中调用restart时会被销毁)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 2015-04-01
    相关资源
    最近更新 更多