· 概況php
· 安裝java
· 基礎python
· 基礎語法linux
· 數據類型git
· 變量web
· 常量算法
· 字符編碼編程
· 字符串格式化json
· listubuntu
· tuple
· dict
· set
· if語句
· for語句
· while語句
· 函數
· 函數定義
· 空函數
· 參數檢查
· 默認參數
· 可變參數
· 關鍵字參數
· 參數組合
· 多個返回值
· 數據類型轉換函數
· 遞歸函數
· 高級特性
· 切片
· 迭代
· 列表生成式
· 生成器
· 函數式編程
· 高階函數
· filter
· sorted
· 返回函數
· 匿名函數
· 裝飾器
· 偏函數
· 模塊
· 建立模塊
· 使用模塊
· 安裝第三方模塊
· 面向對象編程
· 類與實例
· 繼承與多態
· 獲取對象信息
· 綁定屬性與方法
· 多重繼承
· 定製類
· 動態建立類
· 錯誤、調試和測試
· 錯誤處理
· 調試
· 單元測試
· 文檔測試
· IO編程
· 標準輸出
· 標準輸入
· 讀文件
· 寫文件
· 操做文件和目錄
· 經常使用內建模塊
1. 特色:
a) 優雅、明確、簡單。
b) 跨平臺。
c) 2.x版與3.x版不兼容。
2. 缺點
a) 解釋性語言,與C程序相比運行速度慢。
b) 代碼不能加密。
3. Python解釋器
a) CPython:官方版本解釋器;使用最廣的解釋器;使用C語言開發。
b) IPython:基於CPython的交互式解釋器,即僅交互加強,執行的Python代碼功能同樣。
c) PyPy:採用JIT技術,動態編譯(非解釋執行),執行速度快;與CPython的Python代碼小部分不一樣。
d) Jython:運行在Java平臺上的解釋器,將Python代碼編譯成Java字節碼執行。
e) IronPython:運行在.NET平臺上的解釋器,將Python代碼編譯成.NET字節碼執行。
1. Python環境搭建:略。
2. 執行方式
a) 交互式
b) py文件(python命令)
c) py文件(直接執行,僅限Linux和Mac)
1. 註釋:「#」開頭。
2. 標識符:
a) 首字符必須是字母或下劃線;
b) 非首字符能夠是字母、數字或下劃線;
c) 大小寫敏感。
3. 縮進:未規定幾個空格或Tab,按約定俗成,使用4個空格。
1. 整型
a) 範圍:任意大小的整數。
b) 十六進制:用0x前綴和0-九、a-f表示。
c) 示例:一、100、-8080、0、0xff00、0xa5b4c3d2。
2. 浮點型
a) 科學計數法:用e表示10。
b) 示例:1.2三、3.1四、-9.0一、12.3e八、1.2e-5。
3. 字符串
a) 範圍:以「''」或「""」括起來的任意文本。
b) 轉義:轉義字符「\」,如\n、\t、\\。
c) r:表示字符串不轉義。
d) ''':若是字符串含不少換行,使用\n不便閱讀,可以使用'''化簡。
e) 示例
>>> print('I\'m "OK"!') I'm "OK"! >>> print("I'm \"OK\"!") I'm "OK"! >>> print('\\\t\\') \ \ >>> print(r'\\\t\\' \\\t\\ >>> print('''line1 ... line2 ... line3''') line1 line2 line3
4. 布爾值
a) 注意大小寫:True、False。
b) 運算符:and、or、not。
5. 空值:None。
如下代碼Python解釋器作了兩件事:
str = 'ABC'
1. 在內存中建立了一個'ABC'的字符串;
2. 在內存中建立了一個名爲str的變量,並把它指向'ABC'。
1. 常量:常量還是變量,Python無任何機制保證常量不被修改。
2. 約定:常量名所有大寫。
3. 示例
PI = 3.14159265359
1. 默認編碼:ASCII(Python誕生比Unicode發佈時間早)。
2. UTF-8支持:源文件開頭加上。
# -*- coding: utf-8 -*-
3. u:表示字符串使用Unicode編碼。
>>> print('中文') 中文 >>> '中文' '中文'
4. ord函數
a) 聲明
ord(c)
b) 官方說明:Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
c) 示例
>>> ord('A') 65 >>> ord('中') 20013
5. chr函數
a) 聲明
chr(i)
b) 官方說明:Return the string representing a character whose Unicode code point is the integer i.
c) 示例
>>> chr(65) 'A' >>> chr(20013) '中'
6. 編碼間轉換
a) Unicode編碼←→UTF-8編碼
>>> 'ABC'.encode('utf-8') b'ABC' >>> '中文'.encode('utf-8') b'\xe4\xb8\xad\xe6\x96\x87' >>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') '中文'
b) Unicode編碼←→GB2312編碼
>>> '中文'.encode('gb2312') b'\xd6\xd0\xce\xc4' >>> b'\xd6\xd0\xce\xc4'.decode('gb2312') '中文'
7. len函數
a) 聲明
len(s)
b) 官方說明:Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
c) 額外說明:len函數實際調用對象的__len__方法,自定義類可定義該方法,從而使用len函數獲取長度。
d) 示例
>>> len('ABC') 3 >>> len('中文') 2 >>> class Bird(object): ... def __len__(self): ... return 10 ... >>> b = Bird() >>> len(b) 10
1. %運算符:格式化字符串。
2. 佔位符
佔位符 |
類型 |
%d |
整數 |
%f |
浮點數 |
%s |
字符串及任意類型 |
%x |
十六進制整數 |
3. 示例:整數前補空格或0
>>> '%2d-%02d' % (3, 1) ' 3-01'
4. 示例:指定浮點數小數位數
>>> '%.2f' % 3.1415926 '3.14'
5. 示例:%s支持任意類型
>>> 'Age: %s. Gender: %s' % (25, True) 'Age: 25. Gender: True'
6. 示例:%%表示一個%
>>> 'growth rate: %d %%' % 7 'growth rate: 7 %'
1. list:有序集合;元素類型可不一樣。
2. 索引
a) 從0開始。
b) -1表示最後1個元素,-2表示倒數第2個元素。
c) 索引越界報錯:IndexError: list index out of range。
3. len(list)函數:獲取元素個數。
4. list.append(element)函數:末尾追加元素。
5. list.insert(index, element)函數:指定索引位置插入元素。
6. list.pop(index)函數:刪除元素,index默認爲-1。
7. list[index] = element:索引位置替換爲另外一元素。
8. 示例
>>> classmates = ['Michael', 'Bob', 'Tracy'] >>> classmates[0] 'Michael' >>> classmates[1] 'Bob' >>> classmates[-1] 'Tracy' >>> classmates[-2] 'Bob' >>> len(classmates) 3 >>> classmates.append('Adam') >>> classmates ['Michael', 'Bob', 'Tracy', 'Adam'] >>> classmates.insert(1, 'Jack') >>> classmates ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam'] >>> classmates.pop() 'Adam' >>> classmates ['Michael', 'Jack', 'Bob', 'Tracy'] >>> classmates.pop(1) 'Jack' >>> classmates ['Michael', 'Bob', 'Tracy'] >>> classmates[1] = 'Sarah' >>> classmates ['Michael', 'Sarah', 'Tracy'] >>> list0 = ['Apple', 123, True] >>> list1 = ['python', 'java', ['asp', 'php'], 'scheme'] >>> len(list1) 4
9. range函數
a) 聲明
range(stop)
range(start, stop[, step])
b) 官方說明:This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised).
c) 示例
>>> [x for x in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [x for x in range(1, 11)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [x for x in range(0, 30, 5)] [0, 5, 10, 15, 20, 25] >>> [x for x in range(0, 10, 3)] [0, 3, 6, 9] >>> [x for x in range(0, -10, -1)] [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> [x for x in range(0)] [] >>> [x for x in range(1, 0)] []
1. tuple:與list很是相似,可是tuple一旦初始化就不能修改。
2. 函數:除無修改相關的函數外,其餘與list一致。
3. 空tuple:用()表示。
4. 1個元素的tuple(特別注意)
a) (element, ):1個元素的tuple。
b) (element):element自己。因爲括號()既能夠表示tuple,又能夠表示括號運算符,爲避免歧義,Python規定這種狀況下,括號()爲運算符。
5. 示例
>>> tuple = ('Michael', 'Bob', 'Tracy') >>> len(tuple) 3 >>> tuple[0] 'Michael' >>> tuple[-1] 'Tracy' >>> tuple0 = () >>> tuple0 () >>> string0 = ('Python') >>> string0 'Python' >>> tuple1 = ('Python', ) >>> tuple1 ('Python',) >>> tuple3 = ('a', 'b', ['A', 'B']) >>> tuple3[2][0] = 'X' >>> tuple3[2][1] = 'Y' >>> tuple3 ('a', 'b', ['X', 'Y'])
1. dict:與Java的Map相似,使用key-value存儲,具備極快的查找速度;內部存儲順序與key添加順序無關;key必須是不可變對象。
2. dict[key]:獲取value;若是key不存在,則報錯KeyError。
3. dict.get(key, default_value)函數:獲取value;若是key不存在,則返回None或指定的默認值。
4. dict[key] = value:添加key-value或覆蓋key-value。
5. key in dict:若是dict存在key,則返回True,不然返回False。
6. dict.pop(key)函數:刪除key-value。
7. 與list相比,dict特色:
a) 查找和插入的速度極快,不會隨着key的增長而增長;
b) 須要佔用大量的內存,內存浪費多。
8. 示例
>>> scores = {'Michael': 95, 'Bob': 75, 'Tracy': 85} >>> scores0 = dict(Michael=95, Bob=75, Tracy=85) >>> scores1 = dict([('Michael', 95), ('Bob', 75), ('Tracy', 85)]) >>> scores2 = dict({'Michael': 95, 'Bob': 75, 'Tracy': 85}) >>> scores == scores0 == scores1 == scores2 True >>> scores['Adam'] = 67 >>> scores['Adam'] 67 >>> scores['Adam'] = 88 >>> scores['Adam'] 88 >>> scores['Thomas'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Thomas' >>> 'Thomas' in scores False >>> scores.get('Thomas') >>> scores.get('Thomas', -1) -1 >>> scores.pop('Bob') 75 >>> scores {'Michael': 95, 'Tracy': 85, 'Adam': 88} >>> dict0 = {} >>> dict0[(1, 2)] = 1 >>> dict0[(1, [2, 3])] = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
1. set:與dict相似,但不存儲value;因爲key不容許重複,因此set無重複key。
2. set.add(element)函數:添加元素;若是是重複元素,則無效果。
3. set.remove(element)函數:刪除元素。
4. set0 | set1:並集。
5. set0 & set1:交集。
6. set0 - set1:差集。
7. 示例
>>> s = set([1, 1, 2, 2, 3]) >>> s set([1, 2, 3]) >>> s.add(4) >>> s set([1, 2, 3, 4]) >>> s.add(4) >>> s set([1, 2, 3, 4]) >>> s.remove(4) >>> s set([1, 2, 3]) >>> set0 = set([1, 2, 3]) >>> set1 = set([2, 3, 4]) >>> set0 & set1 set([2, 3]) >>> set0 | set1 set([1, 2, 3, 4]) >>> set0 - set1 set([1])
1. 完整if語句模板
if <條件判斷1>: <執行1> elif <條件判斷2>: <執行2> elif <條件判斷3>: <執行3> else: <執行4>
2. 執行過程:當條件判斷爲True、非零數值、非空字符串、非空list等時,即執行。
3. 示例
>>> age = 3 >>> if age >= 18: ... print('adult') ... elif age >= 6: ... print('teenager') ... else: ... print('kid') ... kid
1. 完整for語句模板
for <元素> in <循環對象>: <執行1> else: <執行2>
2. 執行過程:循環對象須爲collections模塊的Iterable類型(含next()函數),for語句不斷調用循環對象的next()函數取出元素並執行執行1,直到next()函數raise StopIteration或執行1遇到break語句爲止;若是因爲next()函數raise StopIteration而終止循環,則執行執行2,不然不執行。
3. break和continue語句:與Java一致。
4. 示例
>>> for n in [1, 2, 3, 4, 5]: ... print(n) ... else: ... print('StopIteration') ... 1 2 3 4 5 StopIteration >>> for n in [1, 2, 3, 4, 5]: ... print(n) ... if n > 3: ... break ... else: ... print('StopIteration') ... 1 2 3 4 >>> sum = 0 >>> for n in range(101): ... sum += n ... >>> print(sum) 5050 >>> for ch in 'ABC': ... print(ch) ... A B C
1. 完整while語句模板
while<條件判斷>: <執行1> else: <執行2>
2. 執行過程:若是條件判斷爲True、非零數值、非空字符串、非空list等,則不斷執行執行1,直到條件判斷不成立或遇到break語句爲止;若是因爲條件判斷不成立而終止循環,則執行執行2,不然不執行。
3. break和continue語句:與Java一致。
4. 示例
>>> sum = 0 >>> n = 1 >>> while n < 101: ... sum += n ... n += 1 ... >>> print(sum) 5050
1. 函數定義模板
def <函數名>(<函數參數>): <函數體>
2. 返回值
a) 若是沒有return語句,函數執行完畢後返回None。
b) return None簡寫爲return
3. 示例
>>> def my_abs(x): ... if x >= 0: ... return x ... else: ... return -x ... >>> my_abs(100) 100
1. 空函數:什麼都不作的函數。
2. 空函數模板
def <函數名>(<函數參數>): pass
3. pass語句
a) 用途:佔位符,避免語法錯誤。
b) 示例(除空函數外)
>>> age = 20 >>> if age >= 18: ... pass
1. 參數個數檢查:Python解釋器自動檢查,若是不對,則報錯TypeError。
>>> my_abs(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: my_abs() takes 1 positional argument but 2 were given
2. 參數類型檢查:自行檢查。
>>> my_abs('A') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in my_abs TypeError: '>=' not supported between instances of 'str' and 'int' >>> def my_abs(x): ... if not isinstance(x, (int, float)): ... raise TypeError('bad operand type') ... if x >= 0: ... return x ... else: ... return -x ... >>> my_abs('A') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in my_abs TypeError: bad operand type
3. isinstance函數
a) 聲明
isinstance(object, classinfo)
b) 官方說明:Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
c) 示例
>>> obj = True >>> isinstance(obj, int) True >>> isinstance(obj, bool) True >>> obj = 10 >>> isinstance(obj, int) True >>> isinstance(obj, bool) False
1. 用途:簡化函數調用。
2. 參數順序:必選參數在前,默認參數在後,不然Python的解釋器會報錯。
3. 示例
>>> def enroll(name, gender, age=6, city='Beijing'): ... print('name = %s, gender = %s, age = %d, city = %s' % (name, gender, age, city)) ... >>> enroll('Sarah', 'F') name = Sarah, gender = F, age = 6, city = Beijing >>> enroll('Bob', 'M', 7) name = Bob, gender = M, age = 7, city = Beijing >>> enroll('Adam', 'M', city='Tianjin') name = Adam, gender = M, age = 6, city = Tianjin >>> enroll('Jhon', 'F', city='Tianjin', age=7) name = Jhon, gender = F, age = 7, city = Tianjin
4. 注意:默認參數必須指向不變對象。由於函數定義時默認參數已被初始化,調用函數時,若是默認參數指向的對象改變,則會影響下次調用。
a) 錯誤用法
>>> def add_end(l=[]): ... l.append('END') ... return l ... >>> add_end([1, 2, 3]) [1, 2, 3, 'END'] >>> add_end(['x', 'y', 'z']) ['x', 'y', 'z', 'END'] >>> add_end() ['END'] >>> add_end() ['END', 'END'] >>> add_end() ['END', 'END', 'END']
b) 正確用法
>>> def add_end(l=None): ... if l is None: ... l = [] ... l.append('END') ... return l ... >>> add_end() ['END'] >>> add_end() ['END']
1. 可變參數:傳入參數個數爲任意個(包括0個),在參數前加*號表示。
2. 本質:傳入的可變參數被自動組裝成一個tuple。
3. 將list或tuple的元素當成可變參數傳入:參數前加*號。
4. 示例
>>> def sum(*numbers): ... sum = 0 ... for n in numbers: ... sum += n ... return sum ... >>> sum(1, 2, 3) 6 >>> l = [1, 2, 3] >>> sum(*l) 6 >>> sum() 0
1. 關鍵字參數:傳入參數個數爲任意個(包括0個),在參數前加**號表示。
2. 本質:傳入的關鍵字參數被自動組裝成一個dict。
3. 將dict的key-value當成關鍵字參數傳入:參數前加**號。
4. 示例
>>> def person(name, age, **others): ... print('name =', name, 'age =', age, 'others =', others) ... >>> person('Michael', 30) name = Michael age = 30 others = {} >>> person('Bob', 35, city='Beijing') name = Bob age = 35 others = {'city': 'Beijing'} >>> person('Adam', 45, gender='M', job='Engineer') name = Adam age = 45 others = {'gender': 'M', 'job': 'Engineer'} >>> kw = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, **kw) name = Jack age = 24 others = {'city': 'Beijing', 'job': 'Engineer'}
1. 參數順序:必選參數、默認參數、可變參數、關鍵字參數。
2. 萬能參數:(*args, **kw),可接收任意參數。
3. 示例
>>> def func(a, b, c=0, *args, **kw): ... print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) ... >>> func(1, 2) a = 1 b = 2 c = 0 args = () kw = {} >>> func(1, 2, c=3) a = 1 b = 2 c = 3 args = () kw = {} >>> func(1, 2, 3, 'a', 'b') a = 1 b = 2 c = 3 args = ('a', 'b') kw = {} >>> func(1, 2, 3, 'a', 'b', x=99) a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99} >>> args = (1, 2, 3, 4) >>> kw = {'x': 99} >>> func(*args, **kw) a = 1 b = 2 c = 3 args = (4,) kw = {'x': 99}
1. 本質:多個返回值的本質是返回一個tuple;返回一個tuple可省略括號,同時可以使用多個變量接受一個tuple。
2. 示例
>>> def test_fn(): ... return 1, 'A' ... >>> x, y = test_fn() >>> print(x, y) 1 A >>> z = test_fn() >>> z (1, 'A')
1. int函數
a) 聲明
class int(x=0) class int(x, base=10)
b) 官方說明:Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
c) 示例
>>> int('123') 123 >>> int(12.34) 12
2. float函數
a) 聲明
class float([x])
b) 官方說明:Return a floating point number constructed from a number or string x.
c) 示例
>>> float('12.34') 12.34
3. bool函數
a) 聲明
class bool([x])
b) 官方說明:Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True.
c) 示例
>>> bool(1) True >>> bool('') False
4. str函數
a) 聲明
class str(object='')
b) 官方說明:
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.
If neither encoding nor errors is given, str(object) returns object.__str__(), which is the 「informal」 or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).
If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.
c) 示例
>>> str(1.23) '1.23'
1. 示例
>>> def sum(begin, end): ... if begin >= end: ... return end ... return begin + sum(begin + 1, end) ... >>> sum(1, 100) 5050
2. 注意:遞歸調用次數過多,致使棧溢出(Python未實現尾遞歸優化)
>>> sum(1, 1000000) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in sum File "<stdin>", line 4, in sum File "<stdin>", line 4, in sum [Previous line repeated 994 more times] File "<stdin>", line 2, in sum RecursionError: maximum recursion depth exceeded in comparison
1. 切片:按照必定規則從list、tuple或字符串取出元素,並生成新list、tuple或字符串。
2. lt[:]:取出索引begin至end-1的元素。
3. lt[::]:從索引begin開始至end-1,每隔step個索引取出一個元素。
4. 簡寫
a) 若是省略begin,則begin爲0。
b) 若是省略end,則end爲len(lt)。
c) 若是同時省略begin和end,則表示複製lt。
5. 示例
>>> names = ['Michael', 'Sarah', 'Tracy'] >>> names[0:3] ['Michael', 'Sarah', 'Tracy'] >>> names[:3] ['Michael', 'Sarah', 'Tracy'] >>> names[1:3] ['Sarah', 'Tracy'] >>> names[-2:] ['Sarah', 'Tracy'] >>> names[-2:-1] ['Sarah'] >>> names[:] ['Michael', 'Sarah', 'Tracy'] >>> l = range(100) >>> [x for x in l[:10]] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [x for x in l[-10:]] [90, 91, 92, 93, 94, 95, 96, 97, 98, 99] >>> [x for x in l[10:20]] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> [x for x in l[:10:2]] [0, 2, 4, 6, 8] >>> [x for x in l[::5]] [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] >>> 'ABCDEFG'[:3] 'ABC' >>> 'ABCDEFG'[::2] 'ACEG'
1. enumerate函數(獲得迭代元素及其索引)
a) 聲明
enumerate(sequence, start=0)
b) 官方說明:Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
c) 示例
>>> for index, value in enumerate(['A', 'B', 'C']): ... print(index, value) ... 0 A 1 B 2 C
2. 示例:迭代元素是tuple的list
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print(x, y) ... 1 1 2 4 3 9
3. 示例:迭代dict(共4種方法,性能:第1種最好,第2種略差,第三、4種最差)
>>> scores = {'Michael': 95, 'Bob': 75, 'Tracy': 85} >>> for key in scores: ... print(key, scores[key]) ... Michael 95 Bob 75 Tracy 85 >>> for key, value in scores.items(): ... print(key, value) ... Michael 95 Bob 75 Tracy 85 >>> for key, value in zip(scores.keys(), scores.values()): ... print(key, value) ... Michael 95 Bob 75 Tracy 85
1. 列表生成式:List Comprehensions。
2. 列表生成式模板
a) 模板1:遍歷對象循環(支持嵌套循環)中的元素,獲得新元素,最後生成list。
[<新元素表達式> for <元素0> in <循環對象0> for <元素1> in <循環對象1> ...]
b) 模板2:僅當知足條件時,才計算新元素生成list。
[<新元素表達式> for <元素0> in <循環對象0> for <元素1> in <循環對象1> ... if <條件判斷>]
3. 示例
>>> [n * n for n in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> [n * n for n in range(1, 11) if n % 2 == 0] [4, 16, 36, 64, 100] >>> [m + n for m in 'ABCD' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ', 'DX', 'DY', 'DZ'] >>> [m + n for m in 'ABCD' for n in 'XYZ' if m > 'B' and n > 'X'] ['CY', 'CZ', 'DY', 'DZ']
1. 與列表生成式區別:列表生成式存儲的是元素,佔用內存較大;生成器(generator)存儲的是元素生成算法,佔用內存較小。
2. 生成器模板
a) 模板1:與列表生成器模板1和2一致,只是將[]改成();適用於簡單邏輯。
b) 模板2:定義函數,在函數體內經過yield語句返回元素;適用於複雜邏輯。
3. 迭代方法:通常經過for語句調用生成器的next()函數獲取元素進行迭代。
4. 示例
>>> g1 = (n * n for n in range(1, 11)) >>> for n in g1: ... print(n) ... 1 4 9 16 25 36 49 64 81 100 >>> def gen(): ... for n in range(1, 11): ... yield n * n ... >>> g2 = gen() >>> for n in g2: ... print(n) ... 1 4 9 16 25 36 49 64 81 100
1. 高階函數:將函數做爲參數傳入的函數。
2. 本質
a) 變量可指向函數。
>>> abs <built-in function abs> >>> abs(-10) 10 >>> f = abs >>> f(-10) 10 >>> f <built-in function abs>
b) 函數名也是變量名。
>>> abs = 'ABC' >>> abs(-10) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable
3. 示例
>>> def add(m, n, f): ... return f(m) + f(n) ... >>> add(-5, 6, abs) 11
1. map函數
a) 聲明
map(function, iterable, …)
b) 官方說明:Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().
c) 示例
>>> def f(x): ... return x * x ... >>> [x for x in map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])] [1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x for x in map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])] ['1', '2', '3', '4', '5', '6', '7', '8', '9']
2. reduce函數
a) 聲明
functools.reduce(function, iterable[, initializer])
b) 官方說明:Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
c) 示例
>>> from functools import reduce >>> reduce(add, [1, 3, 5, 7, 9]) 25 >>> reduce(lambda x, y: x + y, [1, 3, 5, 7, 9]) 25
1. 聲明
filter(function, iterable)
2. 官方說明:Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
3. 示例
>>> def is_odd(n): ... return n % 2 == 1 ... >>> [x for x in filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])] [1, 5, 9, 15]
1. 聲明
sorted(iterable, *, key=None, reverse=False)
2. 官方說明:Return a new sorted list from the items in iterable.
3. 示例
>>> sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36] >>> sorted([36, 5, 12, 9, 21], reverse=True) [36, 21, 12, 9, 5]
1. 返回函數:高階函數除了能夠接受函數做爲參數外,還能夠把函數做爲結果值返回。
2. 返回函數注意:每次調用返回函數的函數,都會返回一個新函數。
3. 閉包(closure):簡單理解是,可以讀取其餘函數內部變量的函數。
4. 閉包注意:返回函數不要引用任何循環變量,或者後續會發生變化的變量。
5. 示例:通常方式與閉包方式
>>> def calc_sum(numbers): ... s = 0 ... for n in numbers: ... s += n ... return s ... >>> calc_sum(range(1, 101)) 5050
>>> def lazy_sum(numbers): ... def sum(): ... s = 0 ... for n in numbers: ... s += n ... return s ... return sum ... >>> f = lazy_sum(range(1, 101)) >>> f <function lazy_sum.<locals>.sum at 0x00000084C154E268> >>> f() 5050 >>> f1 = lazy_sum(range(1, 101)) >>> f == f1 False
6. 示例:閉包陷阱與陷阱規避
>>> def count(): ... fs = [] ... for i in range(1, 4): ... def f(): ... return i * i ... fs.append(f) ... return fs ... >>> f1, f2, f3 = count() >>> f1() 9 >>> f2() 9 >>> f3() 9
>>> def count(): ... fs = [] ... for i in range(1, 4): ... def f(j): ... def g(): ... return j * j ... return g ... fs.append(f(i)) ... return fs ... >>> f1, f2, f3 = count() >>> f1() 1 >>> f2() 4 >>> f3() 9
1. 定義方法:lambda關鍵字,冒號前的標識符爲函數參數,無須return語句,表達式就是返回值。
2. 使用方法:
a) 做爲函數參數傳入;
b) 賦值給變量;
c) 做爲函數返回值。
3. 示例
>>> [x for x in map(lambda n: n * n, range(1, 11))] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> f = lambda x, y: x + y >>> f(1, 2) 3 >>> def calc_sum(x, y): ... return lambda: x + y ...
1. 裝飾器:Python除了能支持OOP的decorator外,直接從語法層次支持decorator。
2. f.__name__屬性:每一個函數都有該存儲函數名的屬性。
3. 裝飾器(Decorator):在不修改某函數代碼的狀況下,在執行該函數時動態增長新的功能。
4. 示例:無函數參數的裝飾器
1 # -*- coding: utf-8 -*- 2 import time 3 import functools 4 def log(func): 5 @functools.wraps(func) # 保證now.__name__爲now 6 def wrapper(*args, **kw): 7 print('begin %s()' % func.__name__) 8 ret = func(*args, **kw) 9 print('end %s()' % func.__name__) 10 return ret 11 return wrapper 12 @log 13 def now(): 14 print(time.time()) 15 # 至關於執行log(now) 16 now() 17 print(now.__name__)
python decorator0.py
begin now() 1517555102.5761998 end now() now
5. 示例:有函數參數的裝飾器
1 # -*- coding: utf-8 -*- 2 import time 3 import functools 4 def log(text): 5 def decorator(func): 6 @functools.wraps(func) # 保證now.__name__爲now 7 def wrapper(*args, **kw): 8 print('begin %s %s()' % (text, func.__name__)) 9 ret = func(*args, **kw) 10 print('end %s %s()' % (text, func.__name__)) 11 return ret 12 return wrapper 13 return decorator 14 @log('testarg') 15 def now(): 16 print(time.time()) 17 # 至關於執行log('testarg')(now) 18 now() 19 print(now.__name__)
python decorator1.py
begin testarg now() 1517555185.114952 end testarg now() now
functools.partial函數
a) 聲明
functools.partial(func[,*args][, **keywords])
b) 官方說明:Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords.
c) 說明:把一個函數的某些參數給固定住(也就是設置默認值),返回一個新的函數,調用這個新函數會更簡單。
d) 示例
>>> import functools >>> int2 = functools.partial(int, base=2) >>> int2('1000000') 64 >>> int2('1010101') 85
1. 模塊(Module):一個.py文件就稱之爲一個模塊。
2. 包(Package):按目錄來組織模塊的方法,多級目錄可組成多級層次的包結構。
3. __init__.py文件
a) 每個包目錄下必須有一個__init__.py的文件,不然,Python把這個目錄當成普通目錄;
b) __init__.py能夠是空文件,也能夠有Python代碼。
c) __init__.py自己也是一個模塊,模塊名便是其包名。
d) 引入模塊時,將從頂層包開始一級級執行__init__.py文件中的代碼。
4. 好處
a) 提升代碼可維護性。
b) 編寫代碼沒必要從零開始,當一個模塊編寫完畢,就能夠被其餘地方引用。
c) 避免函數名和變量名衝突。可是也要注意,儘可能不要與內置函數名字衝突。
5. 內置函數
abs() |
dict() |
help() |
min() |
setattr() |
all() |
dir() |
hex() |
next() |
slice() |
any() |
divmod() |
id() |
object() |
sorted() |
ascii() |
enumerate() |
input() |
oct() |
staticmethod() |
bin() |
eval() |
int() |
open() |
str() |
bool() |
exec() |
isinstance() |
ord() |
sum() |
bytearray() |
filter() |
issubclass() |
pow() |
super() |
bytes() |
float() |
iter() |
print() |
tuple() |
callable() |
format() |
len() |
property() |
type() |
chr() |
frozenset() |
list() |
range() |
vars() |
classmethod() |
getattr() |
locals() |
repr() |
zip() |
compile() |
globals() |
map() |
reversed() |
__import__() |
complex() |
hasattr() |
max() |
round() |
|
delattr() |
hash() |
memoryview() |
set() |
|
6. 示例:
目錄 |
類型 |
名稱 |
mycompany/ ├── abc.py ├── __init__.py ├── utils.py ├── web │ ├── __init__.py │ ├── utils.py │ └── www.py └── xyz.py |
包 模塊 模塊 模塊 包 模塊 模塊 模塊 模塊 |
mycompany mycompany.abc mycompany mycompany.utils mycompany.web mycompany.web mycompany.web.utils mycompany.web.www mycompany.xyz |
1. 文件示例:hello.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ' 文檔註釋 ' __author__ = '做者' import sys def test(): args = sys.argv if len(args) == 1: print('Hello, world!') elif len(args) == 2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__ == '__main__': test()
a) 文檔註釋:任何模塊代碼的第一個字符串都被視爲模塊的文檔註釋。
b) 前4行是標準文件模板,但也能夠所有不寫。
c) import sys:導入sys模塊後,就有了指向該模塊的變量sys,能夠訪問sys模塊的全部功能。
d) sys.argv變量:用list存儲了命令行的全部參數。第1個參數永遠是該.py文件名。
e) __name__變量:若是在命令行運行hello模塊,則值爲'__main__';若是引入hello模塊,則值爲其餘值。
2. 模塊別名:經過「import <模塊名> as <別名>」方式爲引入的模塊起別名,便可經過別名訪問模塊功能。
3. 可見性
a) 正常函數和變量是public,可被直接引用。
b) 相似__xxx__變量是特殊變量(如__author__、__name__、__doc__),可被直接引用,本身的變量通常不要用這種變量名。
c) 相似_xxx和__xxx函數或變量是private,不該被直接引用。注意:Python並無一種方法能夠徹底限制訪問private函數或變量,可是從編程習慣上不該引用。
1. 工具
a) Anaconda,支持Windows、macOS和Linux。
b) pip。
2. 模塊搜索路徑
a) 默認搜索:當前目錄、全部已安裝的內置模塊和第三方模塊。
b) 查看搜索路徑:
>>> import sys >>> sys.path ['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']
c) 修改搜索路徑方法1:直接修改sys.path,運行結束後失效。
>>> import sys >>> sys.path.append('/home/netoxi/workspace/testpy')
d) 修改搜索路徑方法2:設置環境變量PYTHONPATH。
1. Python對象
a) 全部數據類型均可視爲對象。
b) 根類:全部類最終都會繼承object類。
2. 類聲明模板
class <類名>(<父類名>): pass
3. 構造方法:__init__方法(只能有1個);第1個參數永遠是self(相似Java的this),其由Python解釋器傳入。
4. 類建立模板
<變量名> = <類名>(<方法參數>)
5. 類中的方法:與普通函數只有一點區別,即第1個參數永遠是self,其由Python解釋器傳入。
6. private屬性:屬性名前加兩個下劃線__,外部不可直接訪問。實際上,Python解釋器將__<屬性名>改成_<類名>__<屬性名>,所以仍可經過_<類名>__<屬性名>訪問(強烈建議不要這樣訪問,解釋器可能會把__<屬性名>改爲不一樣的變量名)。
7. _<屬性名>屬性:一個下劃線_開頭的實例變量,外部可直接訪問,但約定俗成將其視爲private屬性。
8. 特殊屬性:屬性名前和後加兩個下劃線__,外部可直接訪問,不是private變量。不要自定義__<屬性名>__。
9. @property裝飾器:Python內置@property裝飾器負責將方法變成屬性調用。getter方法變成屬性,加上@property;setter方法變成屬性,加上@<屬性名>.setter。
10. 示例
>>> class Student(object): ... def __init__(self, name, gender): ... self.name = name ... self.__gender = gender ... @property ... def score(self): ... return self._score ... @score.setter ... def score(self, value): ... if not isinstance(value, int): ... raise ValueError('score must be an integer!') ... if value < 0 or value > 100: ... raise ValueError('score must between 0 ~ 100!') ... self._score = value ... @property ... def birth(self): ... return self._birth ... @birth.setter ... def birth(self, value): ... self._birth = value ... @property ... def age(self): ... return 2014 - self._birth ... >>> s = Student('Jhon', 'm') >>> s.name 'Jhon' >>> s.name = 'Harry' >>> s.name 'Harry' >>> s.__gender Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute '__gender' >>> s._Student__gender 'm' >>> s.score Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in score AttributeError: 'Student' object has no attribute '_score' >>> s.score = 101 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 13, in score ValueError: score must between 0 ~ 100! >>> s.score = 98 >>> s.score 98 >>> s.birth = 1995 >>> s.age 19
1. 繼承與多態:Python的繼承、多態與C++和Java相似。
2. 示例
>>> class Animal(object): ... def eat(self): ... print('Animal is eating') ... >>> class Dog(Animal): ... def eat(self): ... print('Dog is eating') ... >>> class Dog(Animal): ... def eat(self): ... print('Dog is eating') ... def run(self): ... print('Dog is running') ... >>> class Fish(Animal): ... def eat(self): ... print('Fish is eating') ... def swim(self): ... print('Fish is swimming') ... >>> a = Animal() >>> d = Dog() >>> f = Fish() >>> a.eat() Animal is eating >>> d.eat() Dog is eating >>> d.run() Dog is running >>> f.eat() Fish is eating >>> f.swim() Fish is swimming >>> isinstance(a, Animal) True >>> isinstance(d, Dog) True >>> isinstance(f, Fish) True >>> isinstance(d, Animal) True >>> isinstance(f, Animal) True >>> isinstance(a, Dog) False >>> isinstance(a, Fish) False
1. type函數
a) 聲明
class type(object)
b) 官方說明:With one argument, return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.
c) 示例
>>> type(123) <class 'int'> >>> type('str') <class 'str'> >>> type(isinstance) <class 'builtin_function_or_method'> >>> type(123) == type(456) True >>> type(123) == int True >>> type('abc') == type('123') True >>> type('abc') == str True >>> type('abc') == type(123) False >>> import types >>> def fn(): ... pass ... >>> type(fn) == types.FunctionType True >>> type(isinstance) == types.BuiltinFunctionType True >>> type(lambda x: x) == types.LambdaType True >>> type((x for x in range(10)))==types.GeneratorType True
2. isinstance函數(判斷繼承關係更方便)
a) 聲明
isinstance(object, classinfo)
b) 官方說明:Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
c) 示例
>>> a = Animal() >>> d = Dog() >>> isinstance(d, Animal) True >>> isinstance(d, Dog) True >>> isinstance('a', str) True >>> isinstance(123, int) True >>> isinstance(b'a', bytes) True >>> isinstance([1, 2, 3], (list, tuple)) True >>> isinstance((1, 2, 3), (list, tuple)) True
3. dir函數
a) 聲明
dir([object])
b) 官方說明:Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes. If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__(). The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
i. If the object is a module object, the list contains the names of the module’s attributes.
ii. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
iii. Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
c) 示例
>>> dir('ABC') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
4. *attr函數
a) 聲明
hasattr(object, name)
getattr(object, name[, default])
setattr(object, name, value)
delattr(object, name)
b) 官方說明(hasattr):The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)
c) 官方說明(getattr):Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
d) 官方說明(setattr):This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.
e) 官方說明(delattr):This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.
f) 示例
>>> class MyObject(object): ... def __init__(self): ... self.x = 9 ... self.y = 10 ... >>> obj = MyObject() >>> hasattr(obj, 'x') True >>> hasattr(obj, 'z') False >>> setattr(obj, 'z', 18) >>> hasattr(obj, 'z') True >>> getattr(obj, 'z') 18 >>> delattr(obj, 'z') >>> getattr(obj, 'z') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'MyObject' object has no attribute 'z' >>> getattr(obj, 'z', 28) 28
1. 綁定屬性與方法
a) 正常狀況下,可爲類和實例綁定屬性和方法,這就是動態語言的靈活性。
b) 若是爲類的某個實例綁定屬性和方法,這些綁定的屬性和方法僅對該實例有效,對該類的其餘實例無效。
c) 若是爲類綁定屬性和方法,則這些綁定的屬性和方法對該類的全部實例有效。
2. __slots__屬性
a) 定義類時,限制只能綁定的屬性名。
b) __slots__定義的屬性僅對當前類有效,對子類無效;若是子類也定義__slots__,則子類容許綁定的屬性名就是自身的__slots__加上父類的__slots__。
3. 示例
>>> class Student(object): ... pass ... >>> s = Student() >>> s.name = 'Michael' >>> print(s.name) Michael >>> def set_age(self, age): ... self.age = age ... >>> from types import MethodType >>> s.set_age = MethodType(set_age, s) >>> s.set_age(25) >>> print(s.age) 25 >>> s2 = Student() >>> s2.set_age(25) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'set_age' >>> def set_score(self, score): ... self.score = score ... >>> Student.set_score = set_score >>> s.set_score(100) >>> print(s.score) 100 >>> s2.set_score(99) >>> print(s2.score) 99
>>> class Student(object): ... __slots__ = ('name', ) ... >>> s = Student() >>> s.name = 'Jhon' >>> s.age = 22 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'age'
1. 多重繼承:經過多重繼承,一個子類能夠同時得到多個父類的全部功能。
2. Mixin設計
a) 思路:在設計類的繼承關係時,一般主線都是單一繼承下來,若是須要「混入」額外功能,經過多重繼承實現。
b) 優先考慮經過多重繼承來組合多個Mixin的功能,而不是設計多層次的複雜的繼承關係。
3. 示例
1 class Animal(object): 2 pass 3 # 大類: 4 class Mammal(Animal): 5 pass 6 class Bird(Animal): 7 pass 8 # 功能 9 class RunnableMixin(object): 10 def run(self): 11 print('Running...') 12 class FlyableMixin(object): 13 def fly(self): 14 print('Flying...') 15 # 各類動物: 16 class Dog(Mammal, RunnableMixin): 17 pass 18 class Bat(Mammal, FlyableMixin): 19 pass 20 class Parrot(Bird, FlyableMixin): 21 pass 22 class Ostrich(Bird, RunnableMixin): 23 pass
1. __str__方法
a) 用途:使用print語句打印時被調用,通常供用戶查看。
b) __repr__方法:命令行打印時被調用,通常供開發者調試。
c) 示例
>>> class Student(object): ... def __init__(self, name): ... self.name = name ... def __str__(self): ... return 'Student object (name=%s)' % self.name ... __repr__ = __str__ ... >>> s = Student('Michael') >>> print(s) Student object (name=Michael) >>> s Student object (name=Michael)
2. __iter__方法
a) 用途:對象可以使用for語句循環,for語句不斷調用該迭代對象的next()方法拿到循環的下一個值。
b) 示例
>>> class Fib(object): ... def __init__(self): ... self.a, self.b = 0, 1 # 初始化兩個計數器a,b ... def __iter__(self): ... return self # 實例自己就是迭代對象,故返回本身 ... def __next__(self): ... self.a, self.b = self.b, self.a + self.b # 計算下一個值 ... if self.a > 50: # 退出循環的條件 ... raise StopIteration(); ... return self.a # 返回下一個值 ... >>> for n in Fib(): ... print(n) ... 1 1 2 3 5 8 13 21 34
3. __getitem__方法
a) 用途:使對象可像list那樣經過下標取出元素、切片。
b) 方法參數:下標取出元素時,方法參數爲int;切片時,方法參數爲切片對象slice。
c) 示例
>>> class Fib(object): ... def __getitem__(self, n): ... if isinstance(n, int): # n是索引 ... a, b = 1, 1 ... for x in range(n): ... a, b = b, a + b ... return a ... if isinstance(n, slice): # n是切片 ... start = n.start ... stop = n.stop ... if start is None: ... start = 0 ... a, b = 1, 1 ... L = [] ... for x in range(stop): ... if x >= start: ... L.append(a) ... a, b = b, a + b ... return L ... >>> f = Fib() >>> f[0] 1 >>> f[100] 573147844013817084101 >>> f[0:5] [1, 1, 2, 3, 5] >>> f[:10] [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> f[:10:2] # 沒有對step參數做處理 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
4. __getattr__方法
a) 用途:未找到屬性或方法時,調用__getattr__方法獲取,實現了屬性和方法的動態化。
b) 示例
>>> class Student(object): ... def __init__(self, name): ... self.name = name ... def __getattr__(self, attr): ... if attr == 'gender': ... return 'm' ... if attr == 'age': ... return lambda: 2017 - 1995 ... raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr) ... >>> s = Student('Jhon') >>> s.name 'Jhon' >>> s.gender 'm' >>> s.age <function Student.__getattr__.<locals>.<lambda> at 0x000000F258362E18> >>> s.age() 22 >>> s.score Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 9, in __getattr__ AttributeError: 'Student' object has no attribute 'score'
5. __call__方法
a) 用途:當使用<對象名>()調用時,調用__call__方法,即便對象能像函數同樣被調用。
b) 注意:__call__方法使對象和函數界限模糊化,這兩類都是Callable對象,可經過callable函數判斷。
c) 示例
>>> class Student(object): ... def __init__(self, name): ... self.name = name ... def __call__(self, another): ... print('Hello, %s, my name is %s.' % (another, self.name)) ... >>> s = Student('John') >>> s('Harry') Hello, Harry, my name is John. >>> class Teacher(object): ... pass ... >>> t = Teacher() >>> callable(s) True >>> callable(t) False >>> callable(callable) True >>> callable([1, 2, 3]) False >>> callable(None) False >>> callable('abc') False
1. type函數
a) 聲明
class type(name, bases, dict)
b) 官方說明:Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute.
c) 示例
>>> def sayHello(self, another): ... print("Hello, %s, my name is %s." % (another, self.name)) ... >>> Student = type("Student", (object, ), {"name": "John", "sayHello": sayHello}) >>> s = Student() >>> s.name 'John' >>> s.sayHello("Harry") Hello, Harry, my name is John.
2. metaclass
a) 理解:元數據metadata是描述數據的數據,那麼metaclass就是描述類的類。可把類當作是metaclass建立出來的「實例」,即先定義metaclass,就能夠建立類,最後建立實例。
b) 示例
>>> # metaclass是類的模板,因此必須從`type`類型派生: ... class ListMetaclass(type): ... def __new__(cls, name, bases, attrs): ... attrs['add'] = lambda self, value: self.append(value) ... return type.__new__(cls, name, bases, attrs) ... >>> class MyList(list, metaclass=ListMetaclass): ... pass ... >>> l = MyList() >>> l.add(1) >>> l [1]
3. 我的想法:與Java相似,動態建立類應該較多用於編寫基礎框架,通常開發較少用到。
1. try語句
a) 與Java的try語句相似。
b) 錯誤類型:全部錯誤類型都繼承自BaseException,Python內置錯誤以下。
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning
c) except:當捕獲父錯誤類型時,也會將其子錯誤類型捕獲。所以,except應該優先捕獲子錯誤類型,再捕獲父錯誤類型,不然子錯誤類型except永遠不會捕獲。
d) else:位於最後一個except塊以後。當沒有錯誤發生時,會自動執行else。
e) 自定義錯誤類型:必要時可自定義錯誤類型,不然儘可能使用內置的錯誤類型。
f) 示例
>>> try: ... print('try...') ... r = 10 / int('a') ... print('result:', r) ... except ValueError as e: ... print('ValueError:', e) ... except ZeroDivisionError as e: ... print('ZeroDivisionError:', e) ... else: ... print('no error!') ... finally: ... print('finally...') ... try... ValueError: invalid literal for int() with base 10: 'a' finally... >>> try: ... print('try...') ... r = 10 / int(0) ... print('result:', r) ... except ValueError as e: ... print('ValueError:', e) ... except ZeroDivisionError as e: ... print('ZeroDivisionError:', e) ... else: ... print('no error!') ... finally: ... print('finally...') ... try... ZeroDivisionError: division by zero finally...
2. raise語句
a) 與Java的throw語句相似。
b) 無參數raise語句:若是raise語句無任何參數,則拋出except的錯誤。
c) 示例
>>> def foo(s): ... n = int(s) ... if n==0: ... raise ValueError('invalid value: %s' % s) ... return 10 / n ... >>> def bar(): ... try: ... foo('0') ... except ValueError as e: ... print('ValueError!') ... raise ... >>> bar() ValueError! Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in bar File "<stdin>", line 4, in foo ValueError: invalid value: 0
>>> class FooError(ValueError): ... pass ... >>> def foo(s): ... n = int(s) ... if n==0: ... raise FooError('invalid value: %s' % s) ... return 10 / n ... >>> foo('0') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in foo __main__.FooError: invalid value: 0
1. 調試方法:
a) print打印;
b) assert斷言;
c) logging日誌;
d) pdb斷點;
e) IDE斷點。
2. assert斷言
a) assert語句:表達式爲False時,拋出AssertionError。
b) 關閉assert:啓動Python解釋器時,可經過-O參數關閉斷言,即不執行assert語句。
python -O <腳本>.py
c) 示例
>>> def foo(s): ... n = int(s) ... assert n != 0, 'n is zero!' ... return 10 / n ... >>> foo('0') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in foo AssertionError: n is zero!
3. logging日誌
a) logging模塊:可輸出日誌到控制檯、日誌。
b) 日誌級別:可指定輸出的日誌級別,debug、info、warning、error。
c) 示例
1 import logging 2 logging.basicConfig(level=logging.INFO) 3 try: 4 logging.info('try...') 5 r = 10 / int('0') 6 logging.info('result:%d' % r) 7 except ZeroDivisionError as e: 8 logging.exception(e)
INFO:root:try... ERROR:root:division by zero Traceback (most recent call last): File "d.py", line 5, in <module> r = 10 / int('0') ZeroDivisionError: division by zero
1. 測試驅動開發:TDD,Test-Driven Development。
2. 單元測試:用來對一個模塊、一個函數或者一個類來進行正確性檢驗的測試工做。
3. 好處
a) 確保一個程序模塊的行爲符合咱們設計的測試用例。
b) 若是對代碼作了修改,只須要再跑一遍單元測試。若是經過,說明修改符合測試用例;若是不經過,說明修改不符合測試用例,要麼修改代碼,要麼修改測試。
4. 單元測試編寫方法
a) 測試類須繼承unittest.TestCase。
b) 以test開頭的方法是測試方法,不以test開頭的方法不被認爲是測試方法,測試時不會被執行。
c) 經常使用斷言1:self.assertEquals(x, y),期待x等於y。
d) 經常使用斷言2:期待拋出錯誤。
with self.assertRaises(<錯誤類型>):
<測試的代碼塊>
e) setUp()方法:在每調用一個測試方法以前分別被執行。
f) tearDown()方法:在每調用一個測試方法以後分別被執行。
g) 示例(mydict.py和mydict_test.py)
1 class Dict(dict): 2 def __init__(self, **kw): 3 super(Dict, self).__init__(**kw) 4 def __getattr__(self, key): 5 try: 6 return self[key] 7 except KeyError: 8 raise AttributeError(r"'Dict' object has no attribute '%s'" % key) 9 def __setattr__(self, key, value): 10 self[key] = value
1 import unittest 2 from mydict import Dict 3 class TestDict(unittest.TestCase): 4 def test_init(self): 5 d = Dict(a=1, b='test') 6 self.assertEqual(d.a, 1) 7 self.assertEqual(d.b, 'test') 8 self.assertTrue(isinstance(d, dict)) 9 def test_key(self): 10 d = Dict() 11 d['key'] = 'value' 12 self.assertEqual(d.key, 'value') 13 def test_attr(self): 14 d = Dict() 15 d.key = 'value' 16 self.assertTrue('key' in d) 17 self.assertEqual(d['key'], 'value') 18 def test_keyerror(self): 19 d = Dict() 20 with self.assertRaises(KeyError): 21 value = d['empty'] 22 def test_attrerror(self): 23 d = Dict() 24 with self.assertRaises(AttributeError): 25 value = d.empty
5. 單元測試運行方法
a) -m unittest參數:可一次批量執行單元測試,而且有不少工具支持自動運行。
b) 示例
python -m unittest mydict_test
..... ---------------------------------------------------------------------- Ran 5 tests in 0.001s OK
1. 文檔測試:Python內置的doctest模塊可直接提取註釋中的代碼並執行測試。
2. 好處:既能夠用來測試,又能夠直接做爲示例代碼。
3. 結果判斷
a) doctest嚴格按照Python交互式命令行的輸入和輸出來判斷測試結果是否正確。
b) 測試異常時,能夠用...表示中間一大段煩人的輸出。
4. 示例(mydict.py)
1 class Dict(dict): 2 ''' 3 Simple dict but also support access as x.y style. 4 5 >>> d1 = Dict() 6 >>> d1['x'] = 100 7 >>> d1.x 8 100 9 >>> d1.y = 200 10 >>> d1['y'] 11 200 12 >>> d2 = Dict(a=1, b=2, c='3') 13 >>> d2.c 14 '3' 15 >>> d2['empty'] 16 Traceback (most recent call last): 17 ... 18 KeyError: 'empty' 19 >>> d2.empty 20 Traceback (most recent call last): 21 ... 22 AttributeError: 'Dict' object has no attribute 'empty' 23 ''' 24 def __init__(self, **kw): 25 super(Dict, self).__init__(**kw) 26 27 def __getattr__(self, key): 28 try: 29 return self[key] 30 except KeyError: 31 raise AttributeError(r"'Dict' object has no attribute '%s'" % key) 32 33 def __setattr__(self, key, value): 34 self[key] = value 35 36 if __name__=='__main__': 37 import doctest 38 doctest.testmod()
python mydict.py
1. print函數
a) 聲明
print(*objects, sep=' ', end='\n', file=sys.stdout)
b) 官方說明:Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
2. 示例
>>> print('The quick brown fox', 'jumps over', 'the lazy dog') The quick brown fox jumps over the lazy dog >>> print(300) 300 >>> print(100 + 200) 300 >>> print('100 + 200 =', 100 + 200) 100 + 200 = 300
1. input函數
a) 聲明
input([prompt])
b) 官方說明:If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
2. 示例
>>> name = input('please enter your name: ') please enter your name: netoxi >>> print('hello,', name) hello, netoxi
1. 打開文件對象:
a) open()函數:返回file對象;若是文件不存在,則拋出IOError錯誤。
b) 打開模式:r表示讀文本,rb表示讀二進制。
c) codecs.open()函數:相似open()函數,但可指定字符編碼,避免亂碼。
2. file.read()函數:一次讀取文件所有內容,返回str對象。
3. file.read(size)函數:可反覆調用,每次只讀取size字節的內容。
4. file.readLine()函數:可反覆調用,每次只讀取一行內容。
5. file.next()函數:可以使用for循環file對象,每次只讀取一行內容。
6. file.close()函數:關閉文件。
7. try ... finally語句:用於保證關閉文件。
8. with語句:功能同上,實現自動關閉文件,代碼更簡潔。
9. 示例
>>> try: ... f = open('/home/netoxi/workspace/testpy/helloworld.py', 'r') ... print(f.read()) ... finally: ... if f: ... f.close() ... #!/usr/bin/env python print('Hello World') >>> import codecs >>> with codecs.open('/home/netoxi/workspace/testpy/helloworld.py', 'r', 'utf-8') as f: ... for line in f: ... print(line.strip()) ... #!/usr/bin/env python print('Hello World 你好')
1. 打開文件對象:
a) open()函數:返回file對象。
b) 打開模式:w表示寫文本(覆蓋),a表示寫文件(追加),wb表示寫二進制(覆蓋),ab表示寫二進制(追加)。
c) codecs.open()函數:相似open()函數,但可指定字符編碼,避免亂碼。
2. file.flush()函數:flush內部buffer。
3. file.write(str)函數:寫字符串。
4. file.writelines(seq)函數:寫字符串序列。
5. 示例
>>> with open('/home/netoxi/workspace/testpy/out', 'w') as f: ... for n in range(0, 10): ... f.write(str(n)) ... f.writelines([str(n) for n in range(0, 5)])
1. os模塊:提供與操做系統相關的功能,如當前操做系統信息、當前用戶信息、當前進程信息及操做、目錄及文件操做等。示例:
>>> import os >>> os.name 'posix' >>> os.uname() ('Linux', 'netoxiubuntu', '4.4.0-92-generic', '#115-Ubuntu SMP Thu Aug 10 09:04:33 UTC 2017', 'x86_64') >>> os.getenv('JAVA_HOME') '/opt/installation/java/jdk1.8.0_101' >>> os.environ {'LC_NUMERIC': 'zh_CN.UTF-8', 'WINDOWID': '65011722', 'MANDATORY_PATH': '/usr/share/gconf/ubuntu.mandatory.path', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/netoxi', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', ... }
2. os.path模塊:提供路徑相關操做。
a) os.path.abspath(path)函數:返回絕對路徑。
b) os.path.exists(path)函數:判斷存在。
c) os.path.isfile(path)函數:判斷普通文件。
d) os.path.isdir(path)函數:判斷目錄。
e) os.path.join(path, *paths)函數:鏈接路徑。
f) os.path.split(path)函數:拆分紅兩部分,第二部分是最後級別的目錄或文件。
g) os.path.splitext(path)函數:拆分紅兩部分,第二部分是擴展名。
h) 示例
>>> os.path.abspath('.') '/home/netoxi/workspace/testpy' >>> os.path.exists('.') True >>> os.path.isfile('.') False >>> os.path.isdir('.') True >>> os.path.join('/home/netoxi/workspace', 'testpy/helloworld.py') '/home/netoxi/workspace/testpy/helloworld.py' >>> os.path.split('/home/netoxi/workspace/testpy/helloworld.py') ('/home/netoxi/workspace/testpy', 'helloworld.py') >>> os.path.splitext('/home/netoxi/workspace/testpy/helloworld.py') ('/home/netoxi/workspace/testpy/helloworld', '.py')
3. 目錄/文件操做
a) os.chmod(path, mode)函數:設置權限。
b) os.chown(path, uid, gid)函數:設置owner。
c) os.listdir(path)函數:返回包含path下全部目錄和文件名稱的list。
d) os.mkdir(path[, mode])函數:建立目錄。
e) os.remove(path)函數:刪除文件;若是是目錄,則拋出OSError錯誤。
f) os.rename(src, dst)函數:重命名。
g) os.rmdir(path)函數:刪除目錄;若是目錄非空,則拋出OSError錯誤。
h) 示例
>>> os.mkdir('./mydir') >>> os.rename('./mydir', './mydir0') >>> os.listdir('.') ['helloworld.py', 'encode.py', 'drink.jpg', 'out', 'mydir0'] >>> os.rmdir('./mydir0')
1. 序列化:Python中叫pickling,把變量從內存中變成可存儲或傳輸的過程。
2. 反序列化:Python中叫unpickling,把變量內容從序列化的對象從新讀到內存。
3. cPickle和pickle模塊:
a) 相同:Python提供的兩個序列化模塊,功能同樣
b) 不一樣:前者是C語言編寫、速度快,後者是Python編寫、速度慢。
c) 導入:
1 try: 2 import cPickle as pickle 3 except ImportError: 4 import pickle
4. pickle.dumps函數
a) 聲明
pickle.dumps(obj[, protocol])
b) 官方說明:Return the pickled representation of the object as a string, instead of writing it to a file. If the protocol parameter is omitted, protocol 0 is used. If protocol is specified as a negative value or HIGHEST_PROTOCOL, the highest protocol version will be used.
5. pickle.loads函數
a) 聲明
pickle.loads(string)
b) 官方說明:Read a pickled object hierarchy from a string. Characters in the string past the pickled object’s representation are ignored.
6. pickle.dump函數
a) 聲明
pickle.dump(obj, file[, protocol])
b) 官方說明:Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj). If the protocol parameter is omitted, protocol 0 is used. If protocol is specified as a negative value or HIGHEST_PROTOCOL, the highest protocol version will be used.
7. pickle.load函數
a) 聲明
pickle.load(file)
b) 官方說明:Read a string from the open file object file and interpret it as a pickle data stream, reconstructing and returning the original object hierarchy. This is equivalent to Unpickler(file).load().
8. 示例
>>> import cPickle as pickle >>> d = dict(name='Bob', age=20, score=88) >>> s = pickle.dumps(d) >>> s "(dp1\nS'age'\np2\nI20\nsS'score'\np3\nI88\nsS'name'\np4\nS'Bob'\np5\ns." >>> d1 = pickle.loads(s) >>> d1 {'age': 20, 'score': 88, 'name': 'Bob'}
>>> d = dict(name='Bob', age=20, score=88) >>> f = open('/home/netoxi/workspace/testpy/dump.txt', 'wb') >>> pickle.dump(d, f) >>> f.close() >>> f1 = open('/home/netoxi/workspace/testpy/dump.txt', 'rb') >>> d1 = pickle.load(f1) >>> f1.close() >>> d1 {'age': 20, 'score': 88, 'name': 'Bob'}
1. JSON和Python數據類型對應:
JSON |
Python |
object |
dict |
array |
list |
string |
str,unicode |
number |
int,long,float |
true/false |
True/False |
null |
None |
2. 對象序列化與反序列化
a) 對象序列化時,須指定default函數,將對象轉爲上表中的Python數據類型。
b) 技巧:一般class實例都有__dict__屬性(少數例外,如定義了__slots__的class),是存儲實例變量的dict,可用於將class實例轉爲dict。
c) 對象反序列化時,須指定object_hook函數,將上表中的Python數據類型轉爲對象。
3. json.dumps函數
a) 聲明
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding=」utf-8」, default=None, sort_keys=False, **kw)
b) 官方說明:Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.
4. json.loads函數
a) 聲明
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
b) 官方說明:Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table. If s is a str instance and is encoded with an ASCII based encoding other than UTF-8 (e.g. latin-1), then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to unicode first.
5. 示例
>>> import json >>> d = dict(name='Bob', age=20, score=88) >>> s = json.dumps(d) >>> s '{"age": 20, "score": 88, "name": "Bob"}' >>> json.loads(s) {u'age': 20, u'score': 88, u'name': u'Bob'}
>>> import json >>> class Student(object): ... def __init__(self, name, age, score): ... self.name = name ... self.age = age ... self.score = score ... >>> s = Student('Bob', 20, 88) >>> def student2dict(std): ... return { ... 'name': std.name, ... 'age': std.age, ... 'score': std.score ... } ... >>> json_str = json.dumps(s, default=student2dict) >>> json_str '{"age": 20, "score": 88, "name": "Bob"}' >>> def dict2student(d): ... return Student(d['name'], d['age'], d['score']) ... >>> json.loads(json_str, object_hook=dict2student) <__main__.Student object at 0x7fcfa7436190>
>>> import json >>> class Student(object): ... def __init__(self, name, age, score): ... self.name = name ... self.age = age ... self.score = score ... >>> s = Student('Bob', 20, 88) >>> json.dumps(s, default=lambda obj: obj.__dict__) '{"age": 20, "score": 88, "name": "Bob"}'
1. collections:Python內置集合模塊,提供許多有用的集合類。
2. namedtuple函數
a) 聲明
collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
b) 官方說明:Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable.
c) 說明:建立tuple子類,支持經過屬性名訪問(tuple僅支持經過索引訪問)。
d) 示例
>>> from collections import namedtuple >>> Point = namedtuple('Point', ['x', 'y']) >>> p = Point(1, 2) >>> p.x 1 >>> p.y 2 >>> p[0] 1 >>> p[1] 2
3. deque類
a) deque類:雙向鏈表,插入、刪除效率較高,也適合當作隊列和棧。
b) list類:線性表,插入、刪除效率較低。
c) 示例
>>> from collections import deque >>> d = deque(['a', 'b', 'c']) >>> d.append('x') >>> d.appendleft('y') >>> d deque(['y', 'a', 'b', 'c', 'x']) >>> d.pop() 'x' >>> d.popleft() 'y'
4. defaultdict類
a) defaultdict類:與dict惟一區別是,當訪問的key不存在時,返回默認值。
b) dict類:當訪問的key不存在時,拋出KeyError。
c) 示例
>>> from collections import defaultdict >>> dd = defaultdict(lambda: 'N/A') >>> dd['key1'] = 'abc' >>> dd['key1'] 'abc' >>> dd['key2'] 'N/A'
5. OrderedDict類
a) OrderedDict類:遍歷順序爲key的插入順序。
b) 示例
>>> from collections import OrderedDict >>> od = OrderedDict() >>> od['z'] = 1 >>> od['y'] = 2 >>> od['x'] = 3 >>> for x in od: ... print(x) ... z y X >>> od.keys() ['z', 'y', 'x']
做者:netoxi
出處:http://www.cnblogs.com/netoxi本文版權歸做者和博客園共有,歡迎轉載,未經贊成須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。歡迎指正與交流。