Python中未定义全局名称错误

Python中未定义全局名称错误,python,class,global-variables,Python,Class,Global Variables,我正在用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()

我正在用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
test Traceback(最近一次调用last):文件“buildWebGraph.py”,第40行,在
test()文件“buildWebGraph.py”,第32行,在测试中
myFetchQueue.push(种子)名称错误:未定义全局名称“myFetchQueue”
因此,我猜想类
GRAPHBuilder
FETCHQueue
的对象的构造正在工作,否则我会在输出字符串测试之前出错,但还有一些事情出了问题。你能帮我吗

def __init__(self, seed = "a string"):
    self.seed = seed
    myFetchQueue = fetchQueue.FETCHQueue()
这里,
myFetchQueue
\uuuu init\uuu
函数的局部变量。因此,它将不可用于类中的其他函数。您可能希望将其添加到当前实例,如下所示

    self.myFetchQueue = fetchQueue.FETCHQueue()
    self.myFetchQueue.push(self.seed)
    self.myFetchQueue.pop()
同样,当您访问它时,您必须使用相应的实例来访问它,如下所示

    self.myFetchQueue = fetchQueue.FETCHQueue()
    self.myFetchQueue.push(self.seed)
    self.myFetchQueue.pop()

我猜
self.myFetchQueue.push(seed)
中的seed也应该是self.seed,如果我理解正确的话;D@Matteo正是:)更新了答案。谢谢:“马蒂奥,请考虑接受这个答案,如果它对你有帮助的话:”对不起,我完全忘了!我最终会明白的;D