问题
In my python script, I'm trying to import module in class and use the imported module in the class method.
class test:
import urllib.parse
def __init__(self, url):
urlComponents = urllib.parse.urlsplit(url)
Howerver, when I try to use the test class, such as
test("http://test.com")
I get the error:
NameError: name 'urllib' is not defined
Why import statement in class body do not take effect?
I use python 3.8.1 in windows 10.
回答1:
The import
statement performs a name binding, but names inside the class scope are not directly visible inside methods. This is the same as for any other class name.
>>> 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
You can refer to any class attribute either through the class or the instance instead. This works for imported names as well.
class test:
import urllib.parse
def __init__(self, url):
# V refer to attribute in class
urlComponents = self.urllib.parse.urlsplit(url)
Note that there isn't any advantage to binding a module inside a class, with the exception of hiding the name from the global scope. Usually, you should import at the global scope.
import urllib.parse
class test:
def __init__(self, url):
# V refer to global module
urlComponents = urllib.parse.urlsplit(url)
回答2:
It was self.urllib.parse that you were missing.
If you really want to import a module inside a class you must access it from that class:
class Test:
import urllib.parse as ul
def __init__(self, url):
urlComponents = self.ul.urlsplit(url)
t1 = Test("www.test.com")
print(t1)
Result : <main.Test at 0x5029>
回答3:
Quoting from https://www.python.org/dev/peps/pep-0008/#imports
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
I think it is good practice to put imports at the top of the file.
来源:https://stackoverflow.com/questions/60236653/import-module-in-class-but-nameerror-when-using-module-in-class-method