1

我正在尝试让“泡菜入门”脚本正常工作。我设法从文件中保存了一个泡菜文件,然后加载它。但是当我将泡菜文件保存在一个文件中(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已经导入,但我不知道如何让它工作。

4

1 回答 1

0

这似乎与如何定义与模块相关的类有关。让它工作的一种快速方法是将模块的main组件直接导入pickleLoader

from main import Graph, Node, Link

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

于 2012-04-07T23:58:14.073 回答