Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在类中导入模块,但在使用类中模块方法时发生NameError_Python 3.x_Python Import - Fatal编程技术网

Python 3.x 在类中导入模块,但在使用类中模块方法时发生NameError

Python 3.x 在类中导入模块,但在使用类中模块方法时发生NameError,python-3.x,python-import,Python 3.x,Python Import,在我的python脚本中,我试图在类中导入模块,并在类方法中使用导入的模块 class test: import urllib.parse def __init__(self, url): urlComponents = urllib.parse.urlsplit(url) 然而,当我尝试使用测试类时,例如 test("http://test.com") 我得到一个错误: NameError:未定义名称“urllib” 为什么类主体中的导入语句不生效 我在w

在我的python脚本中,我试图在类中导入模块,并在类方法中使用导入的模块

class test:
    import urllib.parse

    def __init__(self, url):
        urlComponents = urllib.parse.urlsplit(url)
然而,当我尝试使用测试类时,例如

test("http://test.com")
我得到一个错误:

NameError:未定义名称“urllib”

为什么类主体中的导入语句不生效


我在windows 10中使用python 3.8.1。

缺少的是self.urllib.parse

如果确实要在类内导入模块,则必须从该类访问该模块:

class Test:
    import urllib.parse as ul


    def __init__(self, url):
        urlComponents = self.ul.urlsplit(url)

t1 = Test("www.test.com")  
print(t1)

结果:import语句执行名称绑定,但类范围内的名称在方法内不直接可见。这与任何其他类名相同

>>> class Test:
...     a = 2   # bind name on class
...     def get_a(self):
...         return a  # unqualified reference to class attribute
...
>>> Test().get_a()
NameError: name 'a' is not defined
您可以通过类或实例引用任何类属性。这也适用于导入的名称

class test:
    import urllib.parse

    def __init__(self, url):
        #               V refer to attribute in class
        urlComponents = self.urllib.parse.urlsplit(url)
请注意,在类中绑定模块没有任何好处,但在全局范围中隐藏名称除外。通常,您应该在全局范围内导入

import urllib.parse

class test:

    def __init__(self, url):
        #               V refer to global module
        urlComponents = urllib.parse.urlsplit(url)

谢谢你的帮助。这个解释很清楚,对我很有帮助。