开发者

Problem with importing module and NameError: global name 'module' is not defined

Sorry, if this question has been asked before. I've looked around for quite a while and I haven't found a solution.

So I开发者_开发知识库've created a class in the file ResourceOpen.py

class ResourceOpen():

    import urllib.request

    def __init__(self, source):
            try:
                # Try to open URL
                page = urllib.request.urlopen(source)
                self.text = page.read().decode("utf8")
            except ValueError:
                # Fail? Print error.
                print ("Woops!  Can't find the URL.")
                self.text = ''

    def getText(self):
        return self.text

I would like to use this class in another program,youTubeCommentReader.py...

import ResourceOpen
import urllib.request

pageToOpen = "http://www.youtube.com"
resource = ResourceOpen.ResourceOpen(pageToOpen)
text = resource.getText()

Whenever I try and run youTubeCommentReader, I get the error:

Traceback               
    <module>    D:\myPythonProgs\youTubeCommentReader.py
    __init__    D:\myPythonProgs\ResourceOpen.py
NameError: global name 'urllib' is not defined

What am I doing wrong? Also, I should note that ResourceOpen.py works fine when I access the class within the same file.


Don't import on the class level, just do:

import urllib.request

class ResourceOpen():    

    def __init__(self, source):
            try:
                # Try to open URL
                page = urllib.request.urlopen(source)
                self.text = page.read().decode("utf8")
            except ValueError:
                # Fail? Print error.
                print ("Woops!  Can't find the URL.")
                self.text = ''

    def getText(self):
        return self.text

In the other script:

import ResourceOpen
s = ResourceOpen.ResourceOpen('http://google.com')
print(s.getText())

In your case the module is imported just fine, but only added to the classes namespace. You always want imports on the global level.


The problem with your original code is that urllib.request ends up being a class attribute, so you would have to say self.urllib.request.urlopen(...) in your __init__. import's are much better off at the module level.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜