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
所以我猜这个类GRAPHBuilder
和FETCHQueue
工作对象的建设,否则我会前得到一个错误字符串测试得到输出,但其他事情出错了。你可以帮我吗?
我猜在'self.myFetchQueue.push(种子)'中种子也应该是self.seed,如果我理解正确的话...... D – Matteo
@Matteo Exactly :)更新了答案。谢谢:) – thefourtheye
@Matteo请考虑接受这个答案,如果它可以帮助你:) – thefourtheye