在导入的modu中设置属性时修复路径导入

2024-09-29 21:38:42 发布

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

为了缩短时间,我有一个模块可以做到:

MyModule
----mymodule.py
----__init__.py

我的模块.py

^{pr2}$

因此,如果Im位于MyModule文件夹内并打开一个shell,则以下操作有效:

import mymodule
print mymodule.VarA

但是,如果Im在MyModule文件夹之外,并且执行以下操作:

from MyModule import mymodule
print mymodule.VarA

我得到:'module' object has no attribute 'VarA',我想这是因为setattr正在设置VarA在其他地方,要做什么才能使无论从哪里导入模块,VarA在mymodule中都可用?在


Tags: 模块frompyimport文件夹init时间shell
1条回答
网友
1楼 · 发布于 2024-09-29 21:38:42

如果您阅读了^{}的文档:

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

你可以很容易地看到这个。在

我的模块/我的模块.py公司名称:

current_module = __import__(__name__)
print current_module

您的程序将打印如下内容:

^{pr2}$

如果您使用的是Python2.7,可以浏览文档的其余部分,直到以下部分:

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

所以,就这么做吧:

import importlib
current_module = importlib.import_module(__name__)
setattr(current_module, 'VarA', 5)

如果您需要使用早期的2.x版本,请阅读整个部分(对于您的Python版本,而不是上面链接的2.7)。正确的答案有点复杂,也有点老套:

import sys
current_package = importlib.import_module(__name__)
current_module = sys.modules[__name__]
setattr(current_module, 'VarA', 5)

当然,如果你不打算运行MyModule/我的模块.py作为一个顶级脚本,或者execfile或者在上面使用自定义导入逻辑或者类似的东西,你一开始就不需要这种复杂性。一定有人已经import了,所以就这样做:

import sys
current_module = sys.modules[__name__]
setattr(current_module, 'VarA', 5)

当然,最简单的解决方案是:

变量=5

…但是大概有一个很好的理由在你的真实代码中不起作用。在

相关问题 更多 >

    热门问题