【发布时间】:2019-02-07 13:14:03
【问题描述】:
我有两个文件 'mod1.py' 和 'mod2.py'。
mod1 需要请求模块才能运行。但是我没有在 mod1 中导入它们,而是在 mod2 中导入了 request 和 mod1 模块。
但是
我收到一个错误'name 'requests' is not defined'。我知道如果我直接在 mod1 中导入 'request' 模块,它可以正常工作。但我有其他我想使用的模块需要 'request' 模块。 那么我如何导入一次模块并让所有其他模块都可以访问?.
mod1.py
class getUrl():
def __init__(self, url):
self.url = url
def grab_html(self):
html = requests.get(self.url).text
return html
mod2.py
import requests
import mod1
module1 = mod1.getUrl('https://www.wikipedia.org/')
HTML = module1.grab_html()
编辑:完全错误
Traceback (most recent call last):
File "C:\Users\camel\Desktop\test\mod2.py", line 5, in <module>
HTML = module1.grab_html()
File "C:\Users\camel\Desktop\test\mod1.py", line 6, in grab_html
html = requests.get(self.url).text
NameError: name 'requests' is not defined
[Finished in 0.5s with exit code 1]
[shell_cmd: python -u "C:\Users\guru\Desktop\test\mod2.py"]
【问题讨论】:
-
错误来自哪一行?你能发布完整的错误吗?
-
每次需要时都必须
import requests。 -
它会增加内存吗?如果我继续这样做?
-
不,这应该不是问题,但这可能是一种不好的做法,因为您必须手动维护不同文件中的导入。
-
没有。不,这不是一个坏习惯。如果一个模块需要一个库,它必须导入它。您可以使用flake8 来跟踪无用的导入语句。
标签: python python-3.x class module