Dictionaries
類似於Perl中的哈希
like associative arrays or hashes in Perl;
key-value pairs
>>> aDict = {'host': 'earth'} # create dict
>>> aDict['port'] = 80 # add to dict
>>> aDict
{'host': 'earth', 'port': 80}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'earth'
>>> for key in aDict:
... print key, aDict[key]
...
host earth
port 80
Indentation
代碼塊通過縮進來識別
identified by indentation
Contral Statements
if expression1:
if_suite
elif expression2:
elif_suite
else:
else_suite
while expression:
while_suite
>>> foo = 'abc'
>>> for c in foo:
... print c
...
a
b
c
Python provides the range() built-in function to generate
such a list for us. It does exactly what we want, taking
a range of numbers and
generating a list.
>>> for eachNum in range(3):
... print eachNum
...
0
1
2
List Compression
列表解析
>>> squared = [x ** 2 for x in range(4)]
>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2]
open() and file()
打開文件 handle = open(file_name, access_mode = 'r')
access_mode is either 'r' for read, 'w' for write, or 'a'
for append,'+' for dual read-write access and the 'b'
for binary access. default of read-only ('r')
#讀取整個文件 因爲文件中的每行文本已經自帶了換行字符,所以要
抑制print 語句產生的換行符號
filename = raw_input('Enter file name: ')
fobj = open(filename, 'r')
for eachLine in fobj:
print eachLine,
fobj.close()
#file()內建函數,功能等同於open()
Errors and Exceptions
錯誤檢測及異常處理
try:
filename = raw_input('Enter file name: ')
fobj = open(filename, 'r')
for eachLine in fobj:
print eachLine,
fobj.close()
except IOError, e:
print 'file open error:', e
Function
函數
定義函數
def function_name([arguments]):
"optional documentation string"
function_suite
調用函數
>>> addMe2Me([-1, 'abc'])
[-1, 'abc', -1, 'abc']
類
定義類
class ClassName(base_class[es]):
"optional documentation string"
static_member_declarations
method_declarations
__init__() 方法有一個特殊名字, 所有名字開始和結束都有兩個下劃線的方法都是特殊方法。當一個類實例被創建時, __init__() 方法會自動執行, 在類實例創建完畢後執行, 類似構建函數。__init__() 可以被當成構建函數, 不過不象其它語言中的構建函數, 它並不創建實例--它僅僅是你的對象創建後執行的第一個方法。它的目的是執行一些該對象的必要的初始化工作。通過創建自己的 __init__() 方法, 你可以覆蓋默認的 __init__()方法(默認的方法什麼也不做),從而能夠修飾剛剛創建的對象。在這個例子裏,
我們初始化了一個名爲 name的類實例屬性(或者說成員)。這個變量僅在類實例中存在, 它並不是實際類本身的一部分。__init__()需要一個默認的參數, 前一節中曾經介紹過。毫無疑問,你也注意到每個方法都有
的一個參數, self.什麼是 self ? 它是類實例自身的引用。其他語言通常使用一個名爲 this 的標識符。
如何創建類實例
>>> foo1 = FooClass()
Created a class instance for John Doe
self.__class__.__name__ 這個變量表示實例化它的類的名字。
模塊
模塊是一種組織形式, 它將彼此有關係的Python 代碼組織到一個個獨立文件當中。模塊可以包含可執行代碼, 函數和類或者這些東西的組合。當你創建了一個 Python 源文件,模塊的名字就是不帶 .py 後綴的文件名。
>>> import sys
>>> sys.stdout.write('Hello World!\n')
Hello World!
PEP 就是一個 Python 增強提案(Python Enhancement Proposal)
Python 的創始人, Guido van Rossum(Python 終身的仁慈的獨裁者)
實用內建函數
Function Description
dir([obj]) Display attributes of object or the names of global variables if no parameter given
help([obj]) Display object’s documentation string in a pretty-printedformat or enters interactive help if no parameter given
int(obj) Convert object to an integer
len(obj) Return length of object
open(fn, mode) Open file fn with mode ('r' = read, 'w' = write)
range([[start,
]stop[,step]) Return a list of integers that begin at start up tobut not including stop in increments of step; start defaults to 0, and step defaults to 1
raw_input(str) Wait for text input from the user, optional prompt string can be provided
str(obj) Convert object to a string
type(obj) Return type of object (a type object itself!)