2014-01-18 121 views
1

我正在Python中实现我的第一个class,并且正在努力使其工作。我从一个非常简单的例子开始:Python中的全局名称未定义错误

#!/usr/bin/env python 
""" 

""" 
import fetcher as fetcher 
import fetchQueue as fetchQueue 

    def __init__(self, seed = "a string"): 
     self.seed = seed 
     myFetchQueue = fetchQueue.FETCHQueue() 

    def test(self): 
     print "test" 
     myFetchQueue.push(seed) 
     myFetchQueue.pop() 


#Entrance of this script, just like the "main()" function in C. 
if __name__ == "__main__": 
    import sys 
    myGraphBuilder = GRAPHBuilder() 
    myGraphBuilder.test() 

并且这个类应该调用另一个类的方法,我以非常类似的方式定义了另一个类。

#!/usr/bin/env python 
""" 

""" 

from collections import defaultdict 
from Queue import Queue 

class FETCHQueue(): 

    linkQueue = Queue(maxsize=0) 
    visitedLinkDictionary = defaultdict(int) 

    #Push a list of links in the QUEUE 
    def push(linkList): 
     print linkList 

    #Pop the next link to be fetched 
    def pop(): 
     print "pop" 

然而,当我运行的代码,我得到这样的输出:

test Traceback (most recent call last): File "buildWebGraph.py", line 40, in <module> 
    myGraphBuilder.test() File "buildWebGraph.py", line 32, in test 
    myFetchQueue.push(seed) NameError: global name 'myFetchQueue' is not defined 

所以我猜这个类GRAPHBuilderFETCHQueue工作对象的建设,否则我会前得到一个错误字符串测试得到输出,但其他事情出错了。你可以帮我吗?

回答

1
def __init__(self, seed = "a string"): 
    self.seed = seed 
    myFetchQueue = fetchQueue.FETCHQueue() 

这里,myFetchQueue是一个局部变量来的__init__功能。所以,它不能用于课堂上的其他功能。你可能会想将它添加到当前实例,这样

self.myFetchQueue = fetchQueue.FETCHQueue() 

同样的方式,当你访问它,你必须与相应的实例来访问它,像这样

self.myFetchQueue.push(self.seed) 
    self.myFetchQueue.pop() 
+0

我猜在'self.myFetchQueue.push(种子)'中种子也应该是self.seed,如果我理解正确的话...... D – Matteo

+0

@Matteo Exactly :)更新了答案。谢谢:) – thefourtheye

+0

@Matteo请考虑接受这个答案,如果它可以帮助你:) – thefourtheye

相关问题