本文大綱:
\;而括號、方括號、大括號等「閉合操作符」內部的單一語句,可自然跨越多行。if、while 等關鍵字起頭並以冒號結束。Python 靠縮排來切分程式碼組,同一組內的行必須嚴格左對齊,否則會引發語法錯誤。; 作為分隔符。#!/usr/bin/python2.6
#coding=utf-8
name = "Tom"
def prinName(a):
print a
# 縮排相同的一組語句構成一個程式碼塊;num 與前面的區塊已無關
num = 4
print num
print prinName(name)
導入模組時需要指定模組所在目錄路徑:
# mod.py
#!/usr/bin/python2.6
def prinName(a):
print a
b = "Black"
print a+b
# import.py
#!/usr/bin/python2.6
import mod
mod.prinName()
標識符是計算機語言中允許作為名稱的有效字串集合,其中一部分是關鍵字(保留字),不能挪作他用。Python 還有一批「內建」標識符,雖非保留字,但仍不建議使用這些特殊名稱。
Python 標識符規則:
__doc__ 動態取得文檔字串。>>> str.__doc__ 'str(object) -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.' >>> print str.__doc__ str(object) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object
Python 的命名慣例:
_x)不會被 from module import * 導入。__x__)是系統變數,對解釋器有特殊意義。__x)是類的本地變數。_)用來保存最後一個運算式的結果。>>> a = "I love:" >>> b = "pig" >>> print a+b I love:pig >>> print a.__add__(b) I love:pig
Python 檔案結構範例:
#!/usr/bin/python2.6 # (1) 起始行
#coding=utf-8 # 編碼宣告
"""this is test module""" # (2) 模組文檔(文檔字串)
import sys # (3) 模組導入
import os
debug = True
name = "Tom" # (4) 全域變數
class FooClass(object): # (5) 類定義(若有)
"Foo class"
pass
def test():
"test function"
foo = FooClass() # 將類實例化
if debug:
print 'ran test()'
def prinName(a): # (6) 函數定義(若有)
print a
num = 4
print num
print prinName(name)
if __name__ == '__main__': # (7) 主程式
test()
prinName()
關於主程式:無論當前模組是被別的模組導入,還是作為腳本直接執行,這段程式碼都會執行。所有模組都有執行程式碼的能力,最高層級(沒有縮排)的語句會在模組被導入時就執行,不管你需不需要。妥當的做法是:除了真正需要立即執行的程式碼,其餘功能都封裝進函數;只有主程式模組才寫大量頂層可執行碼,供導入的模組則應盡量減少頂層執行碼。
__name__ 用來指示模組該如何被載入:若模組是被導入,__name__ 等於模組名稱;若模組被直接執行,__name__ 則為 "__main__"。
延伸閱讀