Selenium2自動化測試實戰基於Python語言》讀書筆記--第3章
第3章 Python基礎
由於作者寫的這本書完全是以Python語言為基礎的,所以需要讀者具備一定的Python程式設計能力。如果說最好的Python基礎教程,那應該說是《笨方法學Python》了。
3.1 Python哲學
<span style="color:#000000"><code>Python <span style="color:#006666">2.7</span><span style="color:#006666">.13</span> (v2<span style="color:#006666">.7</span><span style="color:#006666">.13</span>:a06454b1afa1, Dec <span style="color:#006666">17</span> <span style="color:#006666">2016</span>, <span style="color:#006666">20</span>:<span style="color:#006666">42</span>:<span style="color:#006666">59</span>) [MSC v<span style="color:#006666">.1500</span> <span style="color:#006666">32</span> bit (Intel)] <span style="color:#000088">on</span> win32 Type <span style="color:#009900">"copyright"</span>, <span style="color:#009900">"credits"</span> <span style="color:#000088">or</span> <span style="color:#009900">"license()"</span> <span style="color:#000088">for</span> more information. >>> import this The Zen <span style="color:#000088">of</span> Python, <span style="color:#000088">by</span> Tim Peters Beautiful <span style="color:#000088">is</span> better than ugly. Explicit <span style="color:#000088">is</span> better than implicit. Simple <span style="color:#000088">is</span> better than complex. Complex <span style="color:#000088">is</span> better than complicated. Flat <span style="color:#000088">is</span> better than nested. Sparse <span style="color:#000088">is</span> better than dense. Readability counts. Special cases aren't special enough <span style="color:#000088">to</span> break <span style="color:#000088">the</span> rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In <span style="color:#000088">the</span> face <span style="color:#000088">of</span> ambiguity, refuse <span style="color:#000088">the</span> temptation <span style="color:#000088">to</span> guess. There should be one<span style="color:#880000">-- and preferably only one --obvious way to do it.</span> Although <span style="color:#000088">that</span> way may <span style="color:#000088">not</span> be obvious <span style="color:#000088">at</span> <span style="color:#000088">first</span> unless you're Dutch. Now <span style="color:#000088">is</span> better than never. Although never <span style="color:#000088">is</span> often better than *right* now. If <span style="color:#000088">the</span> implementation <span style="color:#000088">is</span> hard <span style="color:#000088">to</span> explain, <span style="color:#000088">it</span>'s a bad idea. If <span style="color:#000088">the</span> implementation <span style="color:#000088">is</span> easy <span style="color:#000088">to</span> explain, <span style="color:#000088">it</span> may be a good idea. Namespaces are one honking great idea <span style="color:#880000">-- let's do more of those!</span> >>> </code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
翻譯為中文就是:
- 優美勝於醜陋
- 明瞭勝於晦澀
- 簡單勝過複雜
- 扁平勝於巢狀
- 間隔勝於緊湊
- 可讀性很重要
- 即使假錯特例的實用性之名,也不違背這些規則
- 雖然實用性次於純度
- 錯誤不應該被無聲的忽略
- 除非明確的沉默
- 當存在多種可能時,不要嘗試去猜測
- 應該有一個,最好只有一個,很明顯可以做到這一點
- 雖然這種方式可能不容易,除非你是Python之父
- 現在做總比不做好
- 雖然過期從未比現在好
- 如果這個實現不容易解釋,那麼它肯定是壞主意
- 如果這個實現容易解釋,那麼它很可能是個好主意
- 名稱空間是一種絕妙的理念,應當多加利用
3.2 輸出與輸入
3.2.1 print列印
Python提供print()方法來列印資訊:
<span style="color:#000000"><code class="language-python">>>><span style="color:#000088">print</span> (<span style="color:#009900">"hello python"</span>) hello python</code></span>
- 1
- 2
列印變數:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>name = <span style="color:#009900">"zhangsan"</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"hello %s , Nice to meet you!"</span> % name)
hello zhangsan , Nice to meet you!
<span style="color:#006666">>>> </span>name = <span style="color:#009900">"Lisi"</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"hello %s , Nice to meet you!"</span> % name)
hello Lisi , Nice to meet you!</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
%s 只能列印字串,如果想要列印陣列,需要使用%d:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>age = <span style="color:#006666">27</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"You are %d !"</span> % age)
You are <span style="color:#006666">27</span> !</code></span>
- 1
- 2
- 3
如果不知道自己列印的型別,可以使用%r:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>age = <span style="color:#006666">27</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"You are %d !"</span> % age)
You are <span style="color:#006666">27</span> !
<span style="color:#006666">>>> </span>
<span style="color:#006666">>>> </span>n =<span style="color:#006666">100</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"You print is %r ."</span> % n)
You <span style="color:#000088">print</span> <span style="color:#000088">is</span> <span style="color:#006666">100</span> .
<span style="color:#006666">>>> </span>n = <span style="color:#009900">"abc"</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"You print is %r ."</span> % n)
You <span style="color:#000088">print</span> <span style="color:#000088">is</span> <span style="color:#009900">'abc'</span> .
<span style="color:#006666">>>> </span>name = <span style="color:#009900">"zhangsan"</span>
<span style="color:#006666">>>> </span>age = <span style="color:#006666">22</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"student info: %s %d ."</span> % (name, age))
student info: zhangsan <span style="color:#006666">22</span> .</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
3.2.2 input輸入
如果希望列印的是程式執行過程中由使用者來決定的內容,可以使用input()方法:
<span style="color:#000000"><code class="language-python">n = input(<span style="color:#009900">"Enter any content: "</span>)
<span style="color:#000088">print</span> <span style="color:#009900">"Your input is %r"</span> % n</code></span>
- 1
- 2
執行上述指令碼時,使用者輸入的資訊就會被打印出來。
3.2.3 引號與註釋
Python不區分單引號、雙引號,都可以用來表示一個字串:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"hello"</span>)
hello
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">'hello'</span>)
hello</code></span>
- 1
- 2
- 3
- 4
單引號和雙引號可以相互巢狀使用,但不能交叉使用:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"你說:'早上你好'"</span>)
你說:<span style="color:#009900">'早上你好'</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">'我說:"今天天氣不錯"'</span>)
我說:<span style="color:#009900">"今天天氣不錯"</span>
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> (<span style="color:#009900">"你微笑著'向我道別"</span>。<span style="color:#009900">')
SyntaxError: invalid syntax</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Python的單行註釋使用“#”表示:
<span style="color:#000000"><code class="language-python">>>><span style="color:#880000">#單行註釋</span>
>>><span style="color:#000088">print</span> (<span style="color:#009900">"hello world"</span>) <span style="color:#880000">#列印hello world</span>
hello world</code></span>
- 1
- 2
- 3
多行註釋使用三對引號表示,同樣不區分單、雙引號:
<span style="color:#000000"><code class="language-python"><span style="color:#009900">"""
我們實現一個偉大的程式
那麼是
print 一行資料 ^_^
"""</span>
<span style="color:#009900">'''
This is a
Multi line comment
'''</span>
<span style="color:#000088">print</span> (<span style="color:#009900">"Hello World"</span>)</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
3.3 分支與迴圈
結構化程式實質上是由有限個順序、分支和迴圈三種基本結構排列、巢狀而成。
3.3.1 if語句
if實現分支判斷,一般語法為:if…else…
<span style="color:#000000"><code class="language-python">>>>a = <span style="color:#006666">2</span>
>>>b = <span style="color:#006666">3</span>
>>><span style="color:#000088">if</span> a > b:
<span style="color:#000088">print</span> (<span style="color:#009900">"a max!"</span>)
<span style="color:#000088">else</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"b max!"</span>)
b max!</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
注意: Python沒有像其他語言一樣使用“{}”表示語句體,而是通過語句的縮排來判斷語句體,縮排預設為4個空格。
if語句通過“==”運算子判斷相等:
<span style="color:#000000"><code class="language-python">>>>student = <span style="color:#009900">"xiaoming"</span>
>>><span style="color:#000088">if</span> student == <span style="color:#009900">"xiaoming"</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"xiaoming, You are on duty today."</span>)
<span style="color:#000088">else</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"Please call xiaoming to duty"</span>)
xiaoming, You are on duty today.</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
if語句通過“!=”運算子判斷不相等;
if語句還可以使用“in”、“not in”表示包含關係:
<span style="color:#000000"><code class="language-python">>>>hi = <span style="color:#009900">"hello world"</span>
>>><span style="color:#000088">if</span> <span style="color:#009900">"hello"</span> <span style="color:#000088">in</span> hi:
<span style="color:#000088">print</span> (<span style="color:#009900">"Contain"</span>)
<span style="color:#000088">else</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"Not Contain"</span>)
Contain</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
if語句還可以進行布林型別的判斷:
<span style="color:#000000"><code class="language-python">>>>a = <span style="color:#000088">True</span>
>>><span style="color:#000088">if</span> a:
<span style="color:#000088">print</span> (<span style="color:#009900">"a is True"</span>)
<span style="color:#000088">else</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"a is not True"</span>)
a <span style="color:#000088">is</span> <span style="color:#000088">True</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
練習:
<span style="color:#000000"><code class="language-python">results = <span style="color:#006666">72</span>
<span style="color:#000088">if</span> results >= <span style="color:#006666">90</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"優秀"</span>)
<span style="color:#000088">elif</span> results >= <span style="color:#006666">70</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"良好"</span>)
<span style="color:#000088">elif</span> results >= <span style="color:#006666">60</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"及格"</span>)
<span style="color:#000088">else</span>:
<span style="color:#000088">print</span> (<span style="color:#009900">"不及格"</span>)</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
答案:良好。
3.3.2 for語句
Python提供了兩種迴圈:while迴圈、for迴圈。
for迴圈的使用更加靈活、簡單,可以直接對一個字串進行遍歷:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">for</span> i <span style="color:#000088">in</span> <span style="color:#009900">"hello world"</span>:
<span style="color:#000088">print</span> (i)
h
e
l
l
o
w
o
r
l
d</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
對一個字典進行遍歷:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>fruits = [<span style="color:#009900">'banana'</span>, <span style="color:#009900">'apple'</span>, <span style="color:#009900">'mango'</span>]
<span style="color:#006666">>>> </span><span style="color:#000088">for</span> fruit <span style="color:#000088">in</span> fruits:
<span style="color:#000088">print</span> fruit
banana
apple
mango</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
使用range()函式來進行指定次數的迴圈:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">for</span> i <span style="color:#000088">in</span> range(<span style="color:#006666">5</span>):
<span style="color:#000088">print</span> (i)
<span style="color:#006666">0</span>
<span style="color:#006666">1</span>
<span style="color:#006666">2</span>
<span style="color:#006666">3</span>
<span style="color:#006666">4</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
注意: range()函式預設從0開始迴圈。
指定起始位置和步長的迴圈:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">for</span> i <span style="color:#000088">in</span> range(<span style="color:#006666">1</span>, <span style="color:#006666">10</span>, <span style="color:#006666">2</span>):
<span style="color:#000088">print</span> (i)
<span style="color:#006666">1</span>
<span style="color:#006666">3</span>
<span style="color:#006666">5</span>
<span style="color:#006666">7</span>
<span style="color:#006666">9</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
range(start, end[, step])
start表示開始位置、end表示結束位置、step表示每一次迴圈的步長。
python2:range() 是一個生成器,xrange()是一個數組,功能完全一樣,效能後者優於前者;
python3:range()和xrange()相同,都是一個數組。
3.4 陣列與字典
3.4.1 陣列
陣列:用方括號[]表示,裡面的每一項用逗號“,”分隔。
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>lists = [<span style="color:#006666">1</span>, <span style="color:#006666">2</span>, <span style="color:#006666">3</span>, <span style="color:#009900">'a'</span>, <span style="color:#006666">5</span>]
<span style="color:#006666">>>> </span>lists
[<span style="color:#006666">1</span>, <span style="color:#006666">2</span>, <span style="color:#006666">3</span>, <span style="color:#009900">'a'</span>, <span style="color:#006666">5</span>]
<span style="color:#006666">>>> </span>lists[<span style="color:#006666">0</span>]
<span style="color:#006666">1</span>
<span style="color:#006666">>>> </span>lists[<span style="color:#006666">4</span>]
<span style="color:#006666">5</span>
<span style="color:#006666">>>> </span>lists[<span style="color:#006666">4</span>] = <span style="color:#009900">'b'</span>
<span style="color:#006666">>>> </span>lists[<span style="color:#006666">4</span>]
<span style="color:#009900">'b'</span>
<span style="color:#006666">>>> </span>lists.append(<span style="color:#009900">'c'</span>)
<span style="color:#006666">>>> </span>lists
[<span style="color:#006666">1</span>, <span style="color:#006666">2</span>, <span style="color:#006666">3</span>, <span style="color:#009900">'a'</span>, <span style="color:#009900">'b'</span>, <span style="color:#009900">'c'</span>]</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
注意:
- Python允許在數組裡任意地防止數字或字串
- 陣列下標是從0開始
- append()函式可以向陣列末尾追加新項
3.4.2 字典
字典:用花括號{}表示,裡面的項是成對出現,一個key對應一個value,key與value之間用冒號分隔,不同的項之間用逗號“,”分隔。
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>dicts = {<span style="color:#009900">"username"</span>:<span style="color:#009900">"zhangsan"</span>,<span style="color:#009900">'password'</span>:<span style="color:#006666">123456</span>}
<span style="color:#006666">>>> </span>dicts.keys()
[<span style="color:#009900">'username'</span>, <span style="color:#009900">'password'</span>]
<span style="color:#006666">>>> </span>dicts.values()
[<span style="color:#009900">'zhangsan'</span>, <span style="color:#006666">123456</span>]
<span style="color:#006666">>>> </span>dicts.items()
[(<span style="color:#009900">'username'</span>, <span style="color:#009900">'zhangsan'</span>), (<span style="color:#009900">'password'</span>, <span style="color:#006666">123456</span>)]
<span style="color:#006666">>>> </span><span style="color:#000088">for</span> k,v <span style="color:#000088">in</span> dicts.items():
<span style="color:#000088">print</span> (<span style="color:#009900">"dicts keys is %r"</span> % k)
<span style="color:#000088">print</span> (<span style="color:#009900">"dicts values is %r"</span> % v)
dicts keys <span style="color:#000088">is</span> <span style="color:#009900">'username'</span>
dicts values <span style="color:#000088">is</span> <span style="color:#009900">'zhangsan'</span>
dicts keys <span style="color:#000088">is</span> <span style="color:#009900">'password'</span>
dicts values <span style="color:#000088">is</span> <span style="color:#006666">123456</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
注意: Python規定一個字典中的key必須獨一無二,valuekey相同。
- keys()函式:返回字典key的列表
- values()函式:返回字典value的列表
- items()函式:將所有的字典項以列表方式返回
按存放的順序輸出字典:
<span style="color:#000000"><code class="language-python"><span style="color:#880000"># 通過zip方法合併兩個List為Dictionary</span>
<span style="color:#880000"># 遍歷會按原先的順序</span>
keys = [<span style="color:#009900">"b"</span>, <span style="color:#009900">"a"</span>, <span style="color:#009900">"c"</span>, <span style="color:#009900">"e"</span>, <span style="color:#009900">"d"</span>]
values = [<span style="color:#009900">"2"</span>, <span style="color:#009900">"1"</span>, <span style="color:#009900">"3"</span>, <span style="color:#009900">"5"</span>, <span style="color:#009900">"4"</span>]
<span style="color:#000088">for</span> key,value <span style="color:#000088">in</span> zip(keys, values):
<span style="color:#000088">print</span> (key, value)</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
輸出結果:
b 2
a 1
c 3
e 5
d 4
3.5 函式、類和方法
3.5.1 函式
Python通過def關鍵字來定義函式:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(a, b)</span>:
<span style="color:#000088">print</span> (a + b)
<span style="color:#006666">>>> </span>add(<span style="color:#006666">3</span>, <span style="color:#006666">5</span>)
<span style="color:#006666">8</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
通常函式不會直接列印結果,而是將結果通過return關鍵字返回:
<span style="color:#000000"><code class="language-python">>>><span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(a, b)</span>:
<span style="color:#000088">return</span> a + b
>>>add(<span style="color:#006666">3</span>, <span style="color:#006666">5</span>)
<span style="color:#006666">8</span></code></span>
- 1
- 2
- 3
- 4
如果在呼叫函式時不想傳參,可以為函式設定預設引數:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(a=<span style="color:#006666">1</span>, b=<span style="color:#006666">2</span>)</span>:
<span style="color:#000088">return</span> a + b
<span style="color:#006666">>>> </span>add()
<span style="color:#006666">3</span>
<span style="color:#006666">>>> </span>add(<span style="color:#006666">3</span>, <span style="color:#006666">5</span>)
<span style="color:#006666">8</span></code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
3.5.2 類和方法
在面向物件程式設計的世界裡,一切皆為物件,抽象的一組物件就是類。
eg:汽車是一個類,而張三家的奇瑞汽車就是一個具體的物件。
Python使用class關鍵字來建立類。
<span style="color:#000000"><code class="language-python"><span style="color:#000088">class</span> <span style="color:#4f4f4f">A</span><span style="color:#4f4f4f">(object)</span>:
<span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(self, a, b)</span>:
<span style="color:#000088">return</span> a + b
count = A()
<span style="color:#000088">print</span> (count.add(<span style="color:#006666">3</span>, <span style="color:#006666">5</span>))</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
輸出結果為:8
對上述程式碼分析:
- 建立一個類A(在Python 3中object為所有類的基類,所有類在建立時預設繼承object,所以不宣告繼承object也可以)
- 在類下面建立一個add()方法,注意,方法的第一個引數必須是存在的,一般習慣命名為self,但在呼叫這個方法時不需要為這個引數傳值
一般在建立類時會首先宣告初始化方法__init__(),注意,init的兩側是雙下劃線,當我們在呼叫該類時,可以用來進行一下初始化工作:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">class</span> <span style="color:#4f4f4f">A</span><span style="color:#4f4f4f">(object)</span>:
<span style="color:#000088">def</span> <span style="color:#009900">__init__</span><span style="color:#4f4f4f">(self, a, b)</span>:
self.a = int(a)
self.b = int(b)
<span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(self)</span>:
<span style="color:#000088">return</span> self.a + self.b
count = A(<span style="color:#009900">'4'</span>, <span style="color:#006666">5</span>)
<span style="color:#000088">print</span> (count.add())</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
輸出結果為:9
對上述程式碼分析:
- 當呼叫A類時首先會執行它的__init__()方法,所以需要對其進行傳參
- 初始化的工作就是將輸入的引數型別轉化為int型別,保證程式容錯性
- add()方法可以直接拿初始化方法的self.a和self.b兩個數進行計算
- 所以在呼叫A類下面的add()方法時,不需要再傳參
Python中類的繼承:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">class</span> <span style="color:#4f4f4f">A</span><span style="color:#4f4f4f">()</span>:
<span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(self, a, b)</span>:
<span style="color:#000088">return</span> a + b
<span style="color:#000088">class</span> <span style="color:#4f4f4f">B</span><span style="color:#4f4f4f">(A)</span>:
<span style="color:#000088">def</span> <span style="color:#009900">sub</span><span style="color:#4f4f4f">(self, a, b)</span>:
<span style="color:#000088">return</span> a - b
<span style="color:#000088">print</span> (B().add(<span style="color:#006666">4</span>, <span style="color:#006666">5</span>))</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
輸出結果為:9
對上述程式碼分析:
- 建立一個A類,在下面建立add()方法用於計算兩個引數相加
- 建立一個B類,繼承A類,並且又繼續建立sub()方法用於計算兩個引數相減
- 因為B類繼承了A類,所以B類自然也擁有了add()方法,從而可以直接通過B類呼叫add()方法
3.6 模組
模組=類庫、模組。
3.6.1 引用模組
通過:import…或者from…import…的方式引用模組,eg:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">import</span> time
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> time.ctime()
Mon Mar <span style="color:#006666">19</span> <span style="color:#006666">16</span>:<span style="color:#006666">20</span>:<span style="color:#006666">26</span> <span style="color:#006666">2018</span></code></span>
- 1
- 2
- 3
如果確定只需要使用time下面的ctime()方法,還可以這樣引用,eg:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span><span style="color:#000088">from</span> time <span style="color:#000088">import</span> ctime
<span style="color:#006666">>>> </span><span style="color:#000088">print</span> ctime()
Mon Mar <span style="color:#006666">19</span> <span style="color:#006666">16</span>:<span style="color:#006666">22</span>:<span style="color:#006666">00</span> <span style="color:#006666">2018</span></code></span>
- 1
- 2
- 3
現在使用時就不必告訴Python,ctime()方法是time模組所提供的了。
但是實際情況,可能是我們還需要使用time模組下的sleep()方法,我們也可以這樣引入進來,但是還有其他方法呢,所以我們可以一次性把time模組下的所有方法都引入進來,eg:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">from</span> time <span style="color:#000088">import</span> *
<span style="color:#000088">print</span> ctime()
<span style="color:#000088">print</span> <span style="color:#009900">"休眠兩秒"</span>
sleep(<span style="color:#006666">2</span>)
<span style="color:#000088">print</span> ctime()</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
最終輸出結果是:
<span style="color:#000000"><code class="language-shell"><span style="color:#000000">Mon</span> <span style="color:#000000">Mar</span> 19 16<span style="color:#000000">:46</span><span style="color:#000000">:22</span> 2018
休眠兩秒
<span style="color:#000000">Mon</span> <span style="color:#000000">Mar</span> 19 16<span style="color:#000000">:46</span><span style="color:#000000">:24</span> 2018</code></span>
- 1
- 2
- 3
其中,星號(*),代表了模組下的所有方法。通過匯入模組後,可以使用help檢視模組的doc,eg:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">import</span> time
help(time)</code></span>
- 1
- 2
pip所安裝的Python第三方庫或框架,都可以使用這種方式來檢視。
3.6.2 模組呼叫
一個軟體專案不可能把所有程式碼都放在一個檔案中實現,一般會按照一定規則在不同的目錄和檔案中實現。
建立一個目錄project,並在目錄下建立兩個檔案,結構如下:
<span style="color:#000000"><code><span style="color:#880000">project/</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">pub</span><span style="color:#009900">.</span><span style="color:#880000">py</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">count</span><span style="color:#009900">.</span><span style="color:#880000">py</span></code></span>
- 1
- 2
- 3
在pub.py檔案中建立add函式:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(a, b)</span>:
<span style="color:#000088">return</span> a + b</code></span>
- 1
- 2
在count.py檔案中呼叫pub.py檔案中的add()函式:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">from</span> pub <span style="color:#000088">import</span> add
<span style="color:#000088">print</span> add(<span style="color:#006666">4</span>, <span style="color:#006666">5</span>)</code></span>
- 1
- 2
- 3
輸出結果為:9
這樣就實現了跨檔案的函式呼叫。
注意: 以下情況會在你使用Python3.5版本中出現,在project目錄下,多了一個__pycache__/pub.cpython-35.pyc檔案,它的作用是為了提高模組載入的速度,每個模組都會在__pycache__資料夾中放置該模組的預編譯模組,命名為module.version.pyc,version是模組的預編譯版本編碼,通常會包含Python的版本號,例如在CPython發行版3.5中,pub.py檔案的預編譯檔案就是:__pycache__/pub.cpython-35.pyc。
3.6.3 跨目錄模組呼叫
如果呼叫檔案與被呼叫檔案在一個目錄下面,那麼可以使用上面的方法,但是如果不在同一個目錄下,假設檔案目錄結構如下:
<span style="color:#000000"><code><span style="color:#880000">project/</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">model/</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">pub</span><span style="color:#009900">.</span><span style="color:#880000">py</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">count</span><span style="color:#009900">.</span><span style="color:#880000">py</span></code></span>
- 1
- 2
- 3
- 4
如果還還想在count.py中呼叫add方法,則需要將目錄的完整路徑補全,eg:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">from</span> model.pub <span style="color:#000088">import</span> add
<span style="color:#000088">print</span> add(<span style="color:#006666">4</span>, <span style="color:#006666">5</span>)</code></span>
- 1
- 2
- 3
執行結果,依然是:9
3.6.4 進一步討論跨目錄模組呼叫
目錄結構更加複雜的情況:
<span style="color:#000000"><code><span style="color:#880000">project/</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">model/</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">count</span><span style="color:#009900">.</span><span style="color:#880000">py</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">new_count</span><span style="color:#009900">.</span><span style="color:#880000">py</span>
<span style="color:#880000">|</span><span style="color:#006666">-</span><span style="color:#006666">-</span><span style="color:#880000">test</span><span style="color:#009900">.</span><span style="color:#880000">py</span></code></span>
- 1
- 2
- 3
- 4
- 5
count.py程式碼如下:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">class</span> <span style="color:#4f4f4f">A</span><span style="color:#4f4f4f">()</span>:
<span style="color:#000088">def</span> <span style="color:#009900">add</span><span style="color:#4f4f4f">(self, a, b)</span>:
<span style="color:#000088">return</span> a + b</code></span>
- 1
- 2
- 3
- 4
new_count.py程式碼如下:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">from</span> count <span style="color:#000088">import</span> A
<span style="color:#000088">class</span> <span style="color:#4f4f4f">B</span><span style="color:#4f4f4f">(A)</span>:
<span style="color:#000088">def</span> <span style="color:#009900">sub</span><span style="color:#4f4f4f">(self, a, b)</span>:
<span style="color:#000088">return</span> a - b
resule = B().add(<span style="color:#006666">2</span>, <span style="color:#006666">5</span>)
<span style="color:#000088">print</span> resule</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
輸出結果:7
上述結果沒問題,接下來與model目錄平級建立test.py檔案:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">from</span> model <span style="color:#000088">import</span> new_count
test = new_count()
test.add(<span style="color:#006666">2</span>, <span style="color:#006666">5</span>)</code></span>
- 1
- 2
- 3
- 4
輸出結果,會出現:ImportError: No module named 'count'
通過提示資訊,在new_count.py檔案中,找不到“count”模組,可剛才在執行new_count.py時是可以正常執行的,那麼,要想弄清楚錯誤的原因,首先要知道當Python執行import時到底做了哪些操作?
重點:
當Python在執行import語句時,執行了如下操作:
-
第1步:建立一個新的module物件(它可能包含多個module);
-
第2步:把這個module物件插到sys.module中;
-
第3步:裝載module的程式碼(如果需要,則必須先編譯);
-
第4步:執行新的module中對應的程式碼;
在執行第3步的時候,首先需要找到module程式所在的位置,搜尋的順序是:
當前路徑(以及從當前目錄指定的sys.path),PythonPATH,再後是Python安裝時設定的相關的預設路徑。正因為存在這樣的順序,所以如果當前路徑或PythonPATH中存在於標準module同樣的module,則會覆蓋標準module。也就是說,如果當前目錄下存在xml.py,那麼在執行import xml時匯入的就是當前目錄下的module,而不是系統標準的xml。
瞭解了這些後,我們就可以先構建一個package,以普通module的方式匯入,這樣即可直接訪問此package中各個module,注意,Python2中的package必須包含一個__init__.py的檔案。
所以上面問題的錯誤原因就是:
站在new_count.py的位置,執行from count import A
,可檢視當前目錄下是否存在“count”名字的檔案或目錄,是可以找到的,但是站在test.py的位置,執行from count import A
時,在當前目錄下是找不到“count”名字的檔案或目錄的,所以丟擲異常。
解決辦法:
最簡單的辦法就是將匯入方法修改為from .count import A
,在“count”前面加個點,用來告訴程式count是相對於new_content.py的一個匯入。
上面解決辦法引入的新的問題:
修改new_count.py程式碼如下:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">from</span> .count <span style="color:#000088">import</span> A
<span style="color:#000088">class</span> <span style="color:#4f4f4f">B</span><span style="color:#4f4f4f">(A)</span>:
<span style="color:#000088">def</span> <span style="color:#009900">sub</span><span style="color:#4f4f4f">(self, a, b)</span>:
<span style="color:#000088">return</span> a - b
result = B().add(<span style="color:#006666">2</span>, <span style="color:#006666">5</span>)
<span style="color:#000088">print</span> result</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
當再次執行test.py程式碼時,出現了新的錯誤:
<span style="color:#000000"><code class="language-syslog">Traceback (most recent <span style="color:#000088">call</span> <span style="color:#000088">last</span>):
File <span style="color:#009900">"/tmp/project/model/new_count.py"</span>, line <span style="color:#006666">1</span>, <span style="color:#000088">in</span> <<span style="color:#000088">module</span>>
<span style="color:#000088">from</span> .<span style="color:#009900">count</span> import A
[Finished <span style="color:#000088">in</span> <span style="color:#006666">0.1</span>s <span style="color:#000088">with</span> exit code <span style="color:#006666">1</span>]SystemError: Parent <span style="color:#000088">module</span> <span style="color:#009900">''</span> <span style="color:#000088">not</span> loaded, cannot perform <span style="color:#000088">relative</span> import</code></span>
- 1
- 2
- 3
- 4
這句話的意思是:“未載入父模組,不能執行相對匯入”。
解決辦法:
需要將匯入模組所在目錄新增到系統環境變數PATH目錄下才可以。
修改test.py的程式碼:
<span style="color:#000000"><code class="language-python"><span style="color:#000088">import</span> sys
sys.path.append(<span style="color:#009900">"./model"</span>) <span style="color:#880000">#將model目錄新增到系統環境變數path下</span>
<span style="color:#000088">from</span> model <span style="color:#000088">import</span> new_count
test = new_count()
test.add(<span style="color:#006666">2</span>, <span style="color:#006666">5</span>)</code></span>
- 1
- 2
- 3
- 4
- 5
- 6
輸出結果:7,注意如果是python2版本需要在model目錄下建立init檔案才行。
3.7 異常
Python用異常物件(exception object)來表示異常情況。遇到錯誤後,會引發異常,如果異常物件並未被處理或者捕捉,則程式就會用所謂的回溯(Traceback,一種錯誤資訊)來終止執行。
3.7.1 認識異常
看下面的程式碼:
<span style="color:#000000"><code class="language-python"><span style="color:#006666">>>> </span>open(<span style="color:#009900">"abc.txt"</span>, <span style="color:#009900">'r'</span>)
Traceback (most recent call last):
File <span style="color:#009900">"<stdin>"</span>, line <span style="color:#006666">