【----__init__.py文件的作用以及内容----】【----20180102----】


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__')
      
    • test.py

        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为空)
    • test.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中的类

    • test.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'>
      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值