讀書筆記--《Python基礎教程第二版》--第十章 充電時刻

來源:互聯網
上載者:User

標籤:ja

第10章 充電時刻

10.1 模組

 math cmath

>>> import math>>> math.sin(0)0.0


10.1.1 模組是程式


cat hello.py

#!/usr/bin/env python#coding=utf-8print "Hello ,world"
>>> import math>>> math.sin(0)0.0
>>> import sys>>> sys.path.append(‘/root/python‘) #或者sys.path.expanduser(‘~/python‘)>>> import helloHello ,world


匯入模組的時候會產生pyc檔案,下次匯入的時候會匯入.pyc檔案,匯入模組主要用於定義,比如變數、函數、類等,模組如果被匯入,就不會被再次匯入

即使執行import命令,這樣做,可以避免迴圈匯入,除非使用reload()

>>> reload(hello)Hello ,world<module ‘hello‘ from ‘/root/python/hello.pyc‘>

但是一般不建議使用relaod


10.1.2  模組用於定義

 模組可以保持自己的範圍

 

 1、載入模組中定義函數

 cat hello2.py #!/usr/bin/env python#coding=utf-8def hello():    print "Hello,world!"

 

 >>> import hello2

這意味著hello函數在模組的範圍內被定義了,可以通過下面的方式來訪問


>>> hello2.hello()

Hello,world!


我們可以通過同樣的方法來使用任何模組的全域範圍中定義的名稱

為了讓代碼重用,請將它模組化


2.在模組中增加測試代碼


>>> __name__

‘__main__‘


>>> hello2.__name__

‘hello2‘



# cat hello3.py#!/usr/bin/env python#coding=utf-8def hello():    print "Hello,world!"# testhello()>>> import hello3Hello,world!





加入__name__==‘__main__‘的目的是讓模組在被匯入的時候不執行


# cat hello4.py#!/usr/bin/env python#coding=utf-8def hello():    print "Hello,world!"def test():    hello()if __name__==‘__main__‘:test()


>>> import hello4>>> hello4.hello()Hello,world!>>> hello4.test()Hello,world!


10.1.3  讓你的模組可用

1、將模組放置在正確的位置

>>> import sys,pprint>>> pprint.pprint(sys.path)[‘‘, ‘/usr/lib64/python27.zip‘, ‘/usr/lib64/python2.7‘, ‘/usr/lib64/python2.7/plat-linux2‘, ‘/usr/lib64/python2.7/lib-tk‘, ‘/usr/lib64/python2.7/lib-old‘, ‘/usr/lib64/python2.7/lib-dynload‘, ‘/usr/lib64/python2.7/site-packages‘, ‘/usr/lib64/python2.7/site-packages/gtk-2.0‘, ‘/usr/lib/python2.7/site-packages‘, ‘/root/python‘]

 

 

 /usr/lib64/python2.7/site-packages 是最好的選擇

 

2、告訴編譯器去哪裡找

編輯sys.path


export PYTHONPATH="/Library/Python/2.7/site-packages:{$PYTHONPATH}"  


路徑設定檔 .pth 檔案來實現

 Python 在遍曆已知的庫檔案目錄過程中,如果見到一個 .pth 檔案,就會將檔案中所記錄的路徑加入到 sys.path 設定中,於是 .pth 檔案說指明的庫也就可以被 Python 運行環境找到了。

 .pth 檔案:import預計會被執行,#會被忽略

 


10.1.4 包


本文出自 “小魚的部落格” 部落格,謝絕轉載!

讀書筆記--《Python基礎教程第二版》--第十章 充電時刻

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.