1.__init__.py的作用
那么如果目录中存在该文件,该目录就会被识别为 module package(模块)。
当用 import 导入该目录时,会执行 __init__.py 里面的代码,如果导入模块比较多,用__init__.py 可以实现批量导入。
2.文件层级
│
├──src
│ │
│ └── predictor <- 接入项目文件夹
│ │
│ ├── __init__.py <- 使predictor成为Python模块
│ │
│ ├── predict.py <- 预测文件
│ │
│ └── 其它 <-代码、模型等
│
└── test.py <- 用来测试接入模型
3.predict.py
class Predict:
def __init__(self):
self.batch_size = 128
class Predict_2:
def __init__(self):
self.batch_size = 256
4.__init__.py的示例
- 情形一(__init__.py调用具体类)
-
__init__.py
from src.predictor.predict import Predict print('####__init__')
-
from src import predictor # 引用到目录,然后会自动执行__init__.py导入Predict类 if __name__ == "__main__": b_s = predictor.Predict().batch_size print('####-1',b_s ) b_s_2= predictor.Predict_2().batch_size print('####-2',b_s_2)
-
输出:
####__init__ ####-1 128 Traceback (most recent call last): File "test_20190102.py", line 18, in <module> b_s_2= predictor.Predict_2().batch_size AttributeError: module 'src.predictor' has no attribute 'Predict_2'
-
- 情形二(__init__.py为空)
-
from src.predictor.predict import Predict if __name__ == "__main__": b_s = Predict().batch_size print('####-1',b_s )
-
输出:
####-1 128
-
- 情形三(__init__.py中__all__的作用)
__all__作用到*.py文件,没法作用到*.py中的类
-
from src.predictor import * if __name__ == "__main__": print(dir()) b_s = predict print('####-1',b_s )
-
若__init__.py中不存在__all__或 __all__= [ ],输出:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] Traceback (most recent call last): File "test_20190102.py", line 8, in <module> b_s = predict NameError: name 'predict' is not defined
-
若__init__.py中__all__ = [“predict”],输出:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'predict'] ####-1 <module 'src.predictor.predict' from 'D:\\wonders20180711\\medical-imaging-server\\mri_server_working\\src\\predictor\\predict.py'>
-