Python is free and easy to learn if you know where to start!
注意事項
- python目前有兩個主要的大版本: python2.x python3.x, 變化比較大, 注意所看資料是針對哪個版本的.
- 注意不要再同一個腳本中混合使用tab和空格進行縮進.
- 推薦在終端中使用ipython
- 關于python代碼風格規范, 請參考pep8
- 如果腳本中包換非英文字符, 請再#!/python下一行添加"# coding: utf-8"
數據類型
變量的可變與不可變.
python中基本的數據類型包括:
- number(int, float)
- string
- tuple
- list
- dict
- boolean
其中: number, string, tuple 屬于不可變類型, 其余屬于可變類型.
改變一個數字的值, 實際上是創建了一個新的對象.
In [1]: a = 1
In [3]: id(a)
Out[3]: 140405345671768
In [4]: a = a + 1
In [5]: id(a)
Out[5]: 140405345671744
注意, 這里變量 a 的id變了. string 也是不可變類型, 改變一個字符串的值也會, 也會創建一個新對象. 所以在python應該盡量避免對字符串使用 '+' 的操作, 防止程序執行效率下降.
如果是一個list
In [6]: b = [1]
In [7]: id(b)
Out[7]: 4322169992
In [8]: b.append(1)
In [9]: b
Out[9]: [1, 1]
In [10]: id(b)
Out[10]: 4322169992
我們看到id沒有發生變化.
一切皆是對象
In [12]: dir("hello")
Out[12]:
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
...
...
'capitalize', 'index', .......]
這里我們看到, "hello" 并不是一個簡單的, 猶如在 C 里那樣的字符串, 與他關聯的還有一大堆的方法.
什么是對象? 對象實際上就是 一堆數據與一堆方法的集合.
這里要強調一點, python并非一門純的面向對象的語言, 其中還包括了很多過程式的, 函數式的編程元素.
常用方法
string
'count',
'encode', 'decode',
'startswith', 'endswith',
'find', 'rfind',
'index', 'rindex',
'join',
'upper', 'lower', 'swapcase',
'lstrip', 'rstrip', 'strip',
'replace',
'split', 'rsplit', 'splitlines',
list
'insert',
'append',
'extend',
'count',
'index',
'pop',
'remove',
'reverse', 'sort'
dict
'get',
'setdefault',
'has_key',
'items', 'iteritems', 'iterkeys', 'itervalues',
'keys',
'values',
'pop', 'popitem',
控制結構
if
- true: True, "x", 1, [1], {"a": 1}
- false: False, "", 0, [], {}
operator: and, or, not
for
python中, 沒有類似C中
for( i=1; i<=100; i++ )
式的語句
語法:
for {$var} in [...]:
...
常用函數
range(), xrange().
常用命令
continue, break
函數
語法:
def function_name(arg1[=...], arg2, ...):
pass
重要概念:
- 參數默認值
- 參數unpacking, f(*args, **kv)
- 匿名函數, lambda
- doc string
- 函數副作用
- 裝飾器
類
語法:
Class Class_name():
def __init__():
pass
def other_function():
pass
重要概念:
- self
- 類變量與實例變量, 類方法(靜態函數)與實例方法
- 類的實例化
- 繼承
- 父類方法調用
包
重要概念:
- python path
- import
- _init_.py
測試
作為一個程序員,學會如何測試自己的代碼是必備的技能,而python 在這方面提供了非常完善的基礎設施。
Unittest
Mock
python3.4 加入標準庫 unittest.mock,之前的版本需要另外安裝。
文檔
通過Sphnix可以根據代碼中的 docstring 生成文檔。支持多種輸出格式,例如:html,pdf等。
其他
virtualenv 可以幫助開發者創建一個獨立的python 環境,方便后續的代碼打包(包括依賴包)和發布。