如何公开导入的组件?

2024-09-30 06:15:54 发布

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

我对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

正确的方法是什么?你知道吗


Tags: 文件方法pyimportinitmainresultmyfunc
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:54

你的名字有冲突。不能同时拥有component.py一个component包。当Python导入MyModule.component时,它要么找到component.py模块要么找到component/__init__.py包。你不能两者兼得。你知道吗

在我的OS X上的Python 3.7安装程序中,包获胜:

$ mkdir -p demopackage/nested
$ cat > demopackage/nested.py <<EOF
> print('This is the nested.py module file')
> EOF
$ cat > demopackage/nested/__init__.py <<EOF
> print('This is the nested/__init__.py package file')
> EOF
$ python3.7 -c 'import demopackage.nested'
This is the nested/__init__.py package file

这意味着你的component.py文件永远不会被执行。你知道吗

component.py内容移到component/__init__.py并在那里导入子模块。导入包的子模块时,该模块将自动成为属性。你知道吗

所以您只需删除component.py,然后就可以使用

import MyModule.component.subcomponent

在任何地方,import MyModule.component都足以到达MyModule.component.subcomponent.myfunc()。你知道吗

有关导入系统,请参阅Python参考文档的Submodules section

When a submodule is loaded [...] a binding is placed in the parent module’s namespace to the submodule object. For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule.

我会在MyModule/component/__init__.py文件的顶部使用包相对导入:

from . import submodule

以确保在导入MyModule.component时加载子模块。你知道吗

相关问题 更多 >

    热门问题