
通过一些案例练习来更好地理解 __init__.py 的用法。我们将创建一个简单的 Python 包,并在 __init__.py 中实现不同的功能。
案例一:基本包结构
-
创建包目录结构:
mypackage/ __init__.py module1.py module2.py -
实现
module1.py和module2.py:# mypackage/module1.py def func1(): return "This is function 1 from module1"# mypackage/module2.py def func2(): return "This is function 2 from module2" -
在
__init__.py中导入模块:# mypackage/__init__.py from .module1 import func1 from .module2 import func2 -
测试导入:
# test.py from mypackage import func1, func2 print(func1



















