1

I am implementing my first class in Python and am struggling to make it work. I started with a very simple example:

#!/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()

and this class should call a method of another class I defined in a very similar way.

#!/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"

However when I run the code I get this output:

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

So I guess that the construction of the object of class GRAPHBuilder and FETCHQueue is working, otherwise I would get an error before the string test gets outputed, but something else is going wrong. Can you help me?

1 Answer 1

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

Here, myFetchQueue is a local variable to the __init__ function. So, it will not available to other functions in the class. You might want to add it to the current instance, like this

    self.myFetchQueue = fetchQueue.FETCHQueue()

Same way, when you are accessing it, you have to access it with the corresponding instance, like this

    self.myFetchQueue.push(self.seed)
    self.myFetchQueue.pop()
Sign up to request clarification or add additional context in comments.

2 Comments

and I guess also seed in self.myFetchQueue.push(seed) should be self.seed if I understood correctly... ;D
Yep sorry for that...it completely ran out of my mind! I would have figured out eventually ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.