我对python非常陌生,正在使用python3.5
我有这样的文件结构:
main.py
MyModule/
MyModule/__init__.py
MyModule/component.py
MyModule/component/
MyModule/component/__init__.py # blank
MyModule/component/subcomponent.py
在某些脚本中,我希望能够使用MyModule.component.subcomponent.myfunc()
使用以下两种方法之一:
import MyModule.component
result = MyModule.component.subcomponent.myfunc()
或者
import MyModule.component.subcomponent
result = MyModule.component.subcomponent.myfunc()
我尝试使我的./MyModule/component.py
具有以下内容,但没有成功:
# This didn't expose the subcomponent stuff
from MyModule.component.subcomponent import *
# I tried this too, but it also didn't work
subcomponent = MyModule.component.subcomponent
正确的方法是什么?你知道吗
你的名字有冲突。不能同时拥有
component.py
和一个component
包。当Python导入MyModule.component
时,它要么找到component.py
模块要么找到component/__init__.py
包。你不能两者兼得。你知道吗在我的OS X上的Python 3.7安装程序中,包获胜:
这意味着你的
component.py
文件永远不会被执行。你知道吗将
component.py
内容移到component/__init__.py
并在那里导入子模块。导入包的子模块时,该模块将自动成为属性。你知道吗所以您只需删除
component.py
,然后就可以使用在任何地方,
import MyModule.component
都足以到达MyModule.component.subcomponent.myfunc()
。你知道吗有关导入系统,请参阅Python参考文档的Submodules section:
我会在
MyModule/component/__init__.py
文件的顶部使用包相对导入:以确保在导入
MyModule.component
时加载子模块。你知道吗相关问题 更多 >
编程相关推荐