为了缩短时间,我有一个模块可以做到:
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中都可用?在
如果您阅读了^{} 的文档:
你可以很容易地看到这个。在
我的模块/我的模块.py公司名称:
您的程序将打印如下内容:
^{pr2}$如果您使用的是Python2.7,可以浏览文档的其余部分,直到以下部分:
所以,就这么做吧:
如果您需要使用早期的2.x版本,请阅读整个部分(对于您的Python版本,而不是上面链接的2.7)。正确的答案有点复杂,也有点老套:
当然,如果你不打算运行MyModule/我的模块.py作为一个顶级脚本,或者
execfile
或者在上面使用自定义导入逻辑或者类似的东西,你一开始就不需要这种复杂性。一定有人已经import
了,所以就这样做:当然,最简单的解决方案是:
变量=5
…但是大概有一个很好的理由在你的真实代码中不起作用。在
相关问题 更多 >
编程相关推荐