如何使一个模块可被其他模块访问

时间:2019-02-07 13:14:04

标签: python python-3.x class module

我有两个文件'mod1.py''mod2.py'

mod1 需要请求模块才能运行。但是我没有将它们导入到mod1中,而是将请求和mod1模块都导入了 mod2 中。

但是

我收到错误消息'未定义名称'requests''。我知道如果我直接在 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"]

4 个答案:

答案 0 :(得分:2)

当您导入某物时,它在导入它的模块中成为命名物。请求不是由mod2.py直接使用的,而是由mod1.py直接使用的,因此应该在其中导入请求。

例如,您可以执行此操作。

mod1.py

import requests

class getUrl():
def __init__(self, url):
    self.url = url

def grab_html(self):
    html = requests.get(self.url).text
    return html

mod2.py

import mod1

module1 = mod1.getUrl('https://www.wikipedia.org/')
HTML = module1.grab_html()

# And also access requests via mod1
indirectly = mod1.requests.get('https://www.wikipedia.org/').text

答案 1 :(得分:0)

导入请求应该在mod1.py中,因为它在mod1.py中定义的类的方法中使用。您也可以同时在mod2.py中将其导入两个地方。

答案 2 :(得分:0)

您需要创建一个__init__.py文件(可以为空),以便将包含mod1的文件夹识别为模块。

然后,您可以执行from mod1 import *from path.to.mod1 import *,它将把所有导入内容转移到mod2。查看this的相对答案。我认为这是一种明智的处理方式,因为您可以将所有依赖项放在一个集中的位置。

由于您担心内存利用率,因此请看一下another conversation

答案 3 :(得分:0)

由于您没有在mod2.py中使用请求,因此可以在mod1.py中进行导入请求

如果您担心内存,它将花费与将要在一个脚本中使用的内存相同的数量。但是,如果您打算同时在mod2.py中使用它,则也必须在其中包含它。