2011-02-28 101 views
3

对不起,如果这个问题之前已被问过。我环顾了很长时间,我还没有找到解决方案。问题导入模块和NameError:全局名称'模块'未定义

所以我在文件中创建一个类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 

我想在另一个程序,youTubeCommentReader.py使用这个类...

import ResourceOpen 
import urllib.request 

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

每当我尝试运行youTubeCommentReader,我得到错误:

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

我在做什么错?另外,我应该注意到ResourceOpen.py在我访问同一个文件中的类时工作正常。

回答

5

不导入的一流水平,只是做:

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 

在其他脚本:

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

在你的情况下,导入模块就好了,但只增加了类名称空间。你总是希望在全球层面上进口。

+0

我试过了,它仍然给我同样的错误。这就像ResourceOpen中的import语句在我尝试将其导入另一个程序时被忽略。当我在同一个文件中使用ResourceOpen类时,它完美地工作。 – Albtzrly 2011-02-28 18:48:07

+0

感谢您的帮助,让它工作。 – Albtzrly 2011-02-28 18:55:37

0

您的原始代码的问题是,urllib.request最终是类属性,因此您必须在您的__init__中说self.urllib.request.urlopen(...)。在模块级别,import的效果要好得多。