【问题标题】:Problem with importing module and NameError: global name 'module' is not defined导入模块和 NameError 的问题:未定义全局名称“模块”
【发布时间】:2011-02-28 18:39:54
【问题描述】:

抱歉,如果之前有人问过这个问题。找了好久也没找到解决办法。

所以我在文件 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 可以正常工作。

【问题讨论】:

    标签: python namespaces module


    【解决方案1】:

    不要在类级别上导入,只需这样做:

    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())
    

    在您的情况下,模块被导入就好了,但只添加到类命名空间中。您总是希望在全局级别上进行导入。

    【讨论】:

    • 我已经尝试过了,它仍然给我同样的错误。就像每当我尝试将 ResourceOpen 中的导入语句导入另一个程序时,它都会被忽略。当我在同一个文件中使用 ResourceOpen 类时,它可以完美运行。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多