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

2024-04-19 03:57:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件'mod1.py''mod2.py'。你知道吗

mod1需要请求模块才能工作。但是我没有在mod1中导入它们,而是在mod2中导入了request和mod1模块。你知道吗

但是

我得到一个错误'name'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"]

Tags: 模块inpytestselfurlrequesthtml
3条回答

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

如果您担心内存问题,它将占用与您将在一个脚本中使用它相同的数量。但是如果你正在使用它,如果你也打算在mod2.py中使用它,那么你也必须包含在里面。你知道吗

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

当您导入某个东西时,它在导入它的模块中成为一个命名的东西。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

相关问题 更多 >