gpt4 book ai didi

Python 将多个文件模块中的所有内容导入命名空间

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:57 25 4
gpt4 key购买 nike

假设我有这个:

script.py
module/
__init__.py # just contains: __all__ = ['foo', 'bar']
foo.py # has a function called foo
bar.py # has a function called bar

如果从 script.py 我执行 from module import * 它有效,但要调用 foo 或 bar 函数我必须执行 foo.foo( )/bar.bar().

有没有办法在命名空间中包含 foo 和 bar 函数,这样我就可以通过 foo()/bar() 调用它们?

编辑:接受的答案适用于此示例案例,但经过测试,如果文件名称中包含数字,它似乎不起作用。

例如,如果您将一个名为 bar2.py 的文件和一个名为 hello 的函数添加到模块文件夹,并相应地编辑 __init__.py,那么在script.py 您不能在脚本上直接调用 hello 函数(只需执行 hello()),尽管您可以执行 bar2。 hello(),它可以工作,但不是我想要的。

编辑:经过大量测试后,我发现通过删除 __all__ 并仅保留导入它可以正常工作。

最佳答案

__init__.py中,写下这两条导入语句:

from .foo import foo
from .bar import bar

编辑:如果您的模块名称中有数字。

from foo2 import foo
from bar2 import bar

关于Python 将多个文件模块中的所有内容导入命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55110533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com