导入模块和NameError的问题:未定义全局名称"模块"

Alb*_*rly 3 python namespaces module

对不起,如果之前已经问过这个问题.我环顾了一会儿,我还没有找到解决方案.

所以我在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
Run Code Online (Sandbox Code Playgroud)

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

import ResourceOpen
import urllib.request

pageToOpen = "http://www.youtube.com"
resource = ResourceOpen.ResourceOpen(pageToOpen)
text = resource.getText()
Run Code Online (Sandbox Code Playgroud)

每当我尝试运行youTubeCommentReader时,我都会收到错误消息:

Traceback               
    <module>    D:\myPythonProgs\youTubeCommentReader.py
    __init__    D:\myPythonProgs\ResourceOpen.py
NameError: global name 'urllib' is not defined
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?此外,我应该注意,当我访问同一文件中的类时,ResourceOpen.py工作正常.

Joc*_*zel 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
Run Code Online (Sandbox Code Playgroud)

在另一个脚本中:

import ResourceOpen
s = ResourceOpen.ResourceOpen('http://google.com')
print(s.getText())
Run Code Online (Sandbox Code Playgroud)

在您的情况下,模块导入很好,但只添加到类命名空间.您总是希望在全球范围内进口.