__init__.py一般是为空,用在一个python目录中,标识该目录是一个python的模块包
先上来看一个例子:
1 .: 2 test1 test2 test_init.py 3 4 ./test1: 5 time.py 6 7 ./test2: 8 cpuinfo.py cpuinfo.pyc __init__.py __init__.pyc
test_init.py里面的代码如下:
1 from test2 import cpuinfo 2 from test1 import time 3
time.py里面:
1 import time 2 print time.strftime(‘%Y.%m.%d‘,time.localtime(time.time()))
cpuinfo.py里面:
import platform os = platform.system() print os print platform.platform() print platform.version()
执行结果:
Linux Linux-4.15.0-041500-generic-x86_64-with-Ubuntu-16.04-xenial #201802011154 SMP Thu Feb 1 11:55:45 UTC 2018 Traceback (most recent call last): File "test_init.py", line 2, in <module> from test1 import time ImportError: No module named test1
假如把time.py改成:并在其平行的目录下面加上__init__.py,即可得出:
#import time #print time.time() #print time.strftime(‘%Y.%m.%d‘,time.localtime(time.time())) print "hello world"
下面的结果:
Linux Linux-4.15.0-041500-generic-x86_64-with-Ubuntu-16.04-xenial #201802011154 SMP Thu Feb 1 11:55:45 UTC 2018 hello world
原文地址:https://www.cnblogs.com/dylancao/p/9931662.html
时间: 2024-10-14 18:41:09