Python:使用import<module>而不是from<module>import访问文件夹中的模块*

2024-09-27 00:20:10 发布

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

我有一个嵌套类,类似于

/Foo
    __init__.py
    pitythefoo.py
    kungfoo.py
    /Bar
        __init__.py
        spam.py
        eggs.py

我的__init__.py文件当前有

__all__ = ['pitythefoo', 'kungfoo']对于/Foo/__init__.py文件

__all__ = ['spam', 'eggs']对于/Foo/Bar/__init__.py文件

所以我可以使用

from Foo.Bar import *
spam
eggs

不过,我想访问垃圾邮件和鸡蛋使用

from Foo import Bar
Bar.spam
Bar.eggs

在我的__init__.py文件中是否有一些代码可以用来进行这种导入


Tags: 文件代码frompyimportfooinit垃圾邮件
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:10

您可以通过修改Foo/Bar/__init__.py来绕过它:

__all__ = ['spam', 'eggs']

from . import *

它很管用,但绝对不优雅

编辑
正如Andrea Corbellini在上面的评论中指出的,您可以避免星型导入:

from . import spam
from . import eggs

相关问题 更多 >

    热门问题