標籤:main 模組名 sys span if判斷 ror 變數 訪問 官網
模組
在Python中,一個.py檔案就是一個模組(Module)
使用模組的好處就是大大提高代碼的可維護性,並且可以被其他地方引用。
同時可以避免函數名和變數名的衝突。
Package(包) 每個包目錄下面必須有一個 __init__.py檔案
這個檔案可以是空的,這個檔案對應模組名就是目前的目錄名即包名
模組的使用
Python內建了很多模組
#!/usr/bin/env python# -*- coding:utf-8 -*-# 編寫一個屬於自己的模組
# 檔案的第一個字串被視為模組的文檔注釋‘a test module‘
# 模組作者
__author__ = ‘JoyJoe‘import sysdef test():
# sys.argv使用列表來儲存命令列的所有參數,第一個元素永遠都是檔案名稱 args = sys.argv if len(args) == 1: print ‘Hello world!‘ elif len(args)==2: print ‘Hello, %s‘%args[1] else: print ‘Too many arguments!‘
# 在命令列運行檔案時,Python解譯器會把變數__name__置為 __main__
# 這樣如果在其他地方匯入該模組時if判斷將會失敗
# 一般用於運行測試if __name__ == ‘__main__‘: test()
匯入模組時可以設定別名
try: import cStringIO as StringIOexcept ImportError: import StringIO
try: import jsonexcept ImportError: import simplejson as json
範圍
在Python中,規定__xxx__這樣的變數為特殊變數,如__name__, __author__, __doc__等
Python同樣在類或模組中沒有函數存取權限修飾符
第三方模組安裝
使用官方推薦的pip 也可以使用easy_install
Python非常強大的一個處理映像的工具庫Python Imaging Library (在官網上註冊名PIL)
pip install PIL
import Imageim = Image.open(‘test.png‘)print im.format, im.size, im.modeim.thumbnail((200, 100))im.save(‘thumb.jpg‘, ‘JPEG‘)
常用第三方庫:
MySQL-python
numpy
Jinja2
模組的載入過程:Python解譯器會搜尋目前的目錄下所有已經安裝的內建模組和第三方模組,搜尋路徑存放在sys模組的path變數中
import sysprint sys.path
Python提供了 __future__ 模組,把下一個新版本的特性匯入到目前的版本中
為了適應Python3.x中的字串表示方法,在Py2.7中通過unicode_literals來使用新文法
# still running on Python2.7from __future__ import unicode_literalsprint ‘\‘xxx\‘ is unicode?‘, isinstance(‘xxx‘, unicode)print ‘u\‘xxx\‘ is unicode?‘, isinstance(u‘xxx‘, unicode)print ‘\‘xxx\‘ is str?‘, isinstance(‘xxx‘, str)print ‘b\‘xxx\‘ is str?‘, isinstance(b‘xxx‘, str)
Python3中, 所有字元都視為unicode 如果需要使用二進位字串則必須添加首碼b
Python3中,所有除法都是精確除法
from __future__ import division
[Python筆記]Python學習筆記四