【问题标题】:How to make a module accessible by other modules如何使其他模块可以访问一个模块
【发布时间】: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


【解决方案1】:

当您导入某些东西时,它会在导入它的模块中成为一个命名的东西。请求并没有被 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

【讨论】:

    【解决方案2】:

    导入请求,应该在mod1.py中,因为在mod1.py中定义的类的方法中使用。如果在 mod2.py 中也需要它,您可以在这两个地方导入它。

    【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      如果您担心内存利用率,请查看 another conversation 以了解同样的问题。

      【讨论】:

      • 是的,我搞砸了一些东西并修复了答案。您可以通过from mod1 import * 结转进口
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多