2012-04-07 79 views
1

我正在嘗試使用「鹹菜入門」腳本工作。我設法從一個文件保存一個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已導入,但我不知道如何讓它工作。

回答

0

這似乎與類與模塊相關的定義方式有關。一個快速的方法來讓這種工作對main模塊的組件直接導入pickleLoader

from main import Graph, Node, Link 

一個更好的解決方案可能是通用組件(圖,節點,鏈路)移動到自己的模塊,然後將該模塊導入mainpickleLoader

+0

感謝它的工作。但爲什麼將這3個組件移到不同的模塊更好?這將改變什麼? – 2012-04-08 07:04:19

+1

將它們放在一個單獨的模塊中(並且導入該模塊)將有助於避免名稱空間衝突。目前的方法要求將這些類型帶入當前的命名空間。將它們放在一個單獨的模塊中並導入,這將使它們保持在它們自己的名稱空間中。 – DRH 2012-04-08 13:41:20