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

Sorry if this question has been asked before. I looked around for quite some time, and I did not find a solution.

So, I 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 youTubeCommentReader.py program ...

import ResourceOpen
import urllib.request

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

Whenever I try to start youTubeCommentReader, I get an error message:

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

What am I doing wrong? In addition, I should note that ResourceOpen.py works fine when I access a class in the same file.

+3
source share
2 answers

Do not import at 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 another script:

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

, . .

+5

, urllib.request , self.urllib.request.urlopen(...) __init__. import .

0

Source: https://habr.com/ru/post/1795303/


All Articles