如何快速做企業(yè)網(wǎng)站包括商城網(wǎng)頁(yè)分析工具
為什么 from . import *
不會(huì)導(dǎo)入子模塊
在 Python 中,from . import *
并不會(huì)自動(dòng)導(dǎo)入子模塊。這是因?yàn)?import *
的行為是由模塊的 __all__
變量決定的。如果沒有定義 __all__
,它只會(huì)導(dǎo)入當(dāng)前模塊中定義的頂層變量和函數(shù),而不會(huì)遞歸地導(dǎo)入子模塊。
解決方法
-
顯式導(dǎo)入子模塊:
在__init__.py
文件中顯式導(dǎo)入你希望包含的子模塊。例如:from . import test print('初始化mytest')
-
使用
__all__
:
如果你仍然希望使用from . import *
,你可以在__init__.py
文件中定義__all__
變量,明確指定要導(dǎo)入的子模塊:__all__ = ['test'] print('初始化mytest')
然后在使用
from . import *
時(shí),Python 會(huì)根據(jù)__all__
的定義導(dǎo)入test
模塊。
示例
假設(shè)你的文件結(jié)構(gòu)如下:
/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(顯式導(dǎo)入子模塊):
from . import test print('初始化mytest')
或者使用
__all__
:__all__ = ['test'] print('初始化mytest')
-
my.py:
import mytest mytest.test.myfun()
通過這種方式,你可以確保 test
模塊被正確導(dǎo)入,并且可以在 my.py
中使用 mytest.test.myfun()
。