加载一个pickle文件

时间:2012-04-07 23:06:36

标签: python-2.7 pickle

我正试图让“泡菜入门”脚本正常工作。我设法从文件中保存了一个pickle文件,然后加载它。但是当我将一个pickle文件保存在一个文件中(在这种情况下是main.py)并从另一个文件加载它时,我收到一个错误。我可能错过了一些小事,但无法弄清楚是什么。

main.py

import pickle

class Node:
  """This class represents a node"""

  def __init__(self, value = None):
    self.val = value

  def toString(self):
    return self.val


class Link:
  """This class represents a link between 2 nodes"""

  def __init__(self, sourceNode, targetNode, LinkWigth):
    self.source = sourceNode
    self.target = targetNode
    self.wight = LinkWigth

  def setWeight(self, newWeight):
    self.wight = newWeight

  def toString(self):
    return self.wight

class Graph:
  """This class represents a graph"""

  def __init__(self):
    self.nodes = []
    self.links = []

  def addNode(self, node):
    self.nodes.append(node)

  def addLink(self, link):
    self.links.append(link)

  def getInDegree(self, node):
    counter = 0
    for link in self.links:
      if link.target == node:
        counter +=1
      else:
        print "target is: %s" % link.target.toString()
        print "source is: %s" % link.source.toString()
    return counter

  def toString(self):
    for link in self.links:
        print link.toString()
    for node in self.nodes:
        print node.toString()


if __name__ == "__main__":
    n1 = Node(4)
    l1 = Link(n1, n1, 1)
    g = Graph()
    g.addNode(n1)
    g.addLink(l1)
    pickle.dump(g, open('haha', 'wb') )

pickleLoader.py

import pickle
import main


n = main.Node(44)
print n.toString()
g = pickle.load( open('haha', 'rb') )
print "ha"

错误

C:\Users\R\Desktop\pickle test>main.py

C:\Users\R\Desktop\pickle test>pickleLoader.py
44
Traceback (most recent call last):
  File "C:\Users\R\Desktop\pickle test\pickleLoader.py", line 7, in <module>

    g = pickle.load( open('haha', 'rb') )
  File "C:\Program Files\Python27\lib\pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "C:\Program Files\Python27\lib\pickle.py", line 858, in load
    dispatch[key](self)
  File "C:\Program Files\Python27\lib\pickle.py", line 1069, in load_inst
    klass = self.find_class(module, name)
  File "C:\Program Files\Python27\lib\pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Graph'

C:\Users\R\Desktop\pickle test>

我猜这个问题与命名空间有关,因为导入了main.py,但我不知道如何让它工作。

1 个答案:

答案 0 :(得分:0)

这似乎与如何定义与模块相关的类有关。允许此操作的快速方法是将main模块的组件直接导入pickleLoader

from main import Graph, Node, Link

更好的解决方案可能是将公共组件(图形,节点,链接)移动到它们自己的模块中,然后将该模块导入mainpickleLoader