模塊和模塊的常用方法
1、__init__.py
python的每個模塊的包中,都有一個__init__.py文件,有了這個文件,我們才能導入這個包內的文件。
我們還可以再__init__.py文件中再導入其他的包,或者模塊。這樣,當我們導入這個包的時候,__init__.py文件自動運行。幫我們導入了裏面模塊,我們就不需要將所有的import語句寫在一個文件裏了。
2、__name__
如果模塊是被自己直接執行,那麼__name__的值爲__main__
如果模塊是被導入,那麼__name__的值爲模塊的名字
test1.py
#!/usr/bin/env python
#coding:utf-8
def test():
print'__name__=',__name__
if __name__ == '__main__':
test()
執行結果:__name__= __main__
test2.py
#!/usr/bin/env python
#coding:utf-8
import test1
test1.test()
執行結果:__name__= test1
所以可以用if __name__=='__main__'來防止被導入執行
3、__file__
文件的路徑
4、__doc__
文件的描述
#!/usr/bin/env python
#coding:utf-8
'''
hellohellohello
'''
print __doc__
執行結果:hellohellohello