使用从另一个导入中导入的模块 [英] Using modules imported from another import

查看:50
本文介绍了使用从另一个导入中导入的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理一个重构为较小的.py文件的项目.我注意到很多模块一次又一次地导入到各种文件中.一些语句位于文件中,这些文件将导入另一个文件,而另一个文件具有与导入文件相同的导入语句.例如:

I'm cleaning up a project that was refactored into smaller .py files. I noticed that a lot of modules are being imported again and again in various files. Some statements are in files that import another which has the same import statement used by the importing file. For example:

main.py

import alt
print (os.getcwd())

alt.py

import os

print(os.getcwd())引发 NameError:未定义名称'os'.在alt.py中执行import语句时, os 是否不应该成为 sys.modules 的一部分吗?

The print(os.getcwd()) throws a NameError: name 'os' is not defined. Shouldn't os be part of sys.modules when the import statement is executed in alt.py?

是否可以使用由另一个首先导入的模块导入的模块?

Is it possible to use a module imported by another module that was imported first?

推荐答案

它们在以下命名空间中可用:

They are available in the following namespace:

import alt
print (alt.os.getcwd())

这篇关于使用从另一个导入中导入的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆