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:
In the other script:
In your case the module is imported just fine, but only added to the classes namespace. You always want imports on the global level.