一、.py文件可以看做一個模塊,模塊類似其他語言中封裝的類庫
模塊分類:
內置模塊
自定義模塊
第三方模塊(需要安裝才能使用)
我想要使用cal.py中定義的函數,可以這樣做
例如:cal.py源代碼:
#!/usr/bin/python#coding:utf-8def add( a, b ): return a + b
import_test.py要使用add函數:
`#!/usr/bin/python #coding:utf-8 import cal print cal.add( 10, 20 )`
二,內置屬性name
cal.py
` #!/usr/bin/python
#coding:utf-8 def add( a, b ): return a + b print __name__ ghostwu@ghostwu:~/python$ python cal.py
main
ghostwu@ghostwu:~/python$ python import_test.py
cal
30
ghostwu@ghostwu:~/python$當執行cal.py本身時,__name__被解釋成__main__, 通過模塊引入方式執行時,別解釋成文件名,這個特性有什麼用?
#!/usr/bin/python #coding:utf-8 def add( a, b ): return a + b if __name__ == '__main__': print add( 100, 200 ) ghostwu@ghostwu:~/python$ python import_test.py 30ghostwu@ghostwu:~/python$ python cal.py300`
這就是name的一個小作用,當一個模塊(.py文件)被別的文件調用時,一般是想調用它裏面定義的函數或者方法,我們可以通過name讓外部模塊調用方式,不會執行到類似print add( 100, 200 )這樣的具體業務代碼。只用到裏面的函數或者方法定義。