您的位置:首页 > 汽车 > 时评 > 为什么 from . import * 不会导入子模块

为什么 from . import * 不会导入子模块

2024/10/7 9:44:24 来源:https://blog.csdn.net/weixin_55102248/article/details/140694478  浏览:    关键词:为什么 from . import * 不会导入子模块

为什么 from . import * 不会导入子模块

在 Python 中,from . import * 并不会自动导入子模块。这是因为 import * 的行为是由模块的 __all__ 变量决定的。如果没有定义 __all__,它只会导入当前模块中定义的顶层变量和函数,而不会递归地导入子模块。

解决方法

  1. 显式导入子模块
    __init__.py 文件中显式导入你希望包含的子模块。例如:

    from . import test
    print('初始化mytest')
    
  2. 使用 __all__
    如果你仍然希望使用 from . import *,你可以在 __init__.py 文件中定义 __all__ 变量,明确指定要导入的子模块:

    __all__ = ['test']
    print('初始化mytest')
    

    然后在使用 from . import * 时,Python 会根据 __all__ 的定义导入 test 模块。

示例

假设你的文件结构如下:

	/mnt/d/python_proj				├── my.py		└── mytest├── __init__.py└── test.py
  • mytest/test.py

    def myfun():print("This is myfun in test module")
    
  • mytest/init.py(显式导入子模块):

    from . import test
    print('初始化mytest')
    

    或者使用 __all__

    __all__ = ['test']
    print('初始化mytest')
    
  • my.py

    import mytest
    mytest.test.myfun()
    

通过这种方式,你可以确保 test 模块被正确导入,并且可以在 my.py 中使用 mytest.test.myfun()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com