Import Module In Class, But NameError When Using Module In Class Method
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):
Solution 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)
Solution 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)
Post a Comment for "Import Module In Class, But NameError When Using Module In Class Method"