自動化測試腳本語言-Python 讀書筆記

 

python讀書筆記

 

1         格式說明

 

1,  同一層次的語句必須有相同的縮進。每一組這樣的語句稱爲一個

2,   行結束符號

每個塊語句(函數defif, elseforwhile等) 開始的行 結束

其他的行 沒有結束符號,也可以有分號;

3,   註釋 符號 #

4,   區分大小寫??

5,   賦值語句:    使用等號=

條件判斷語句:使用雙等號==

6,變量不需要申明,直接使用

 

2         函數

函數通過def關鍵字定義def關鍵字後跟一個函數的 標識符 名稱,然後跟一對圓括號。圓括號之中可以包括一些變量名,該行以冒號結尾。接下來是一塊語句,它們是函數體。下面這個例子將說明這事實上是十分簡單的:

 

def printMax(a, b):
    if a > b:
        print a, 'is maximum'
    else:
        print b, 'is maximum'

printMax(3, 4) # directly give literal values

 

2.1   默認參數值

def say(message, times = 1):
    print message * times

say('Hello')
say('World', 5)

 

關鍵參數

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c

func(3, 7)
func(25, c=24)
func(c=50, a=100)

 

 

pass語句在Python中表示一個空的語句塊。

def someFunction():
    pass

 

2.2   在函數中接收元組和列表

當要使函數接收元組字典形式的參數的時候,有一種特殊的方法,它分別使用***前綴。這種方法在函數需要獲取可變數量的參數的時候特別有用。

>>> def powersum(power, *args):
...     '''Return the sum of each argument raised to specified power.'''
...     total = 0
...     for i in args:
...          total += pow(i, power)
...     return total
...
>>> powersum(2, 3, 4)
25    =  3
2+ 42

>>> powersum(2, 10)
100

由於在args變量前有*前綴,所有多餘的函數參數都會作爲一個元組存儲在args。如果使用的是**前綴,多餘的參數則會被認爲是一個字典的鍵/值對

 

3         模塊

爲了在其他程序中重用模塊,模塊的文件名必須.py爲擴展名。

3.1   import

import sys

 

Python下標從0開始計數,而非從1開始。

 

字節編譯的.pyc文件

這些字節編譯的文件也是與平臺無關的。

3.2   from..import語句

如果你想要直接輸入argv變量到你的程序中(避免在每次使用它時打sys.),那麼你可以使用

from sys import argv語句。如果你想要輸入所有sys模塊使用的名字,那麼你可以使用

from sys import *語句。這對於所有模塊都適用。一般說來,應該避免使用from..import而使用import語句,因爲這樣可以使你的程序更加易讀,也可以避免名稱的衝突

3.3   _name_

當一個模塊被第一次輸入的時候,這個模塊的主塊將被運行。假如我們只想在程序本身被使用的時候運行主塊,而在它被別的模塊輸入的時候不運行主塊,我們該怎麼做呢?這可以通過模塊的__name__屬性完成。

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

3.4   使用global語句

如果你想要爲一個定義在函數外的變量賦值,那麼你就得告訴Python這個變量名不是局部的,而是 全局 的。我們使用global語句完成這一功能。沒有global語句,是不可能爲定義在函數外的變量賦值的。

你可以使用同一個global語句指定多個全局變量。例如global x, y, z

3.5   創建你自己的模塊

個模塊應該被放置在我們輸入它的程序的同一個目錄中,或者在sys.path所列目錄之一

#!/usr/bin/python
# Filename: mymodule.py


def sayhi():
    print 'Hi, this is mymodule speaking.'

version = '0.1'

# End of mymodule.py

 

說明: 文件名.py 相當於類名 /結構名,裏面的函數相當於成員函數,裏面的變量相當於成員變量

3.6   使用自己的模塊

#!/usr/bin/python
# Filename: mymodule_demo.py


import mymodule

mymodule.sayhi()
print 'Version', mymodule.version

4         數據結構

4.1   列表【中括號】

由於你可以增加或刪除項目,我們說列表是 可變的 數據類型,即這種類型是可以被改變的。

你可以在列表中添加 任何種類的對象 包括數甚至其他列表

shoplist = ['apple', 'mango', 'carrot', 'banana']

print 'I have', len(shoplist),'items to purchase.'

print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
    print item,

print '/nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist

shoplist.sort()     這個方法影響列表本身,而不是返回一個修改後的列表

olditem = shoplist[0]
del shoplist[0]

 

i = []
 i.append('item')

4.2   列表綜合

通過列表綜合,可以從一個已有的列表導出一個新的列表。例如,你有一個數的列表,而你想要得到一個對應的列表,使其中所有大於2的數都是原來的2倍。對於這種應用,列表綜合是最理想的方法。

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo

4.3   元組 (小括號)

元組和列表十分類似,只不過元組和字符串一樣是 不可變的 即你不能修改元組。元組通過圓括號中用逗號分割的項目定義

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)

4.4   字典{大括號},引用時用[中括號]

字典類似於你通過聯繫人名字查找地址和聯繫人詳細情況的地址簿,即,我們把(名字)和(詳細情況)聯繫在一起。注意,鍵必須是唯一的,就像如果有兩個人恰巧同名的話,你無法找到正確的信息。

注意,你只能使用不可變的對象(比如字符串)來作爲字典的,但是你可以不可變或可變的對象作爲字典的。基本說來就是,你應該只使用簡單的對象作爲鍵。

d = { key1 : value1, key2 : value2 }

注意它們的/值對用冒號分割,而各個對用逗號分割,所有這些都包括在花括號中

ab = {       'Swaroop'   : '[email protected]',
             'Larry'     : '[email protected]',
             'Matsumoto' : '[email protected]',
             'Spammer'   : '[email protected]'
     }
print "Swaroop's address is %s" % ab['Swaroop']

# Adding a key/value pair
ab['Guido'] = '[email protected]'       添加

# Deleting a key/value pair
del ab['Spammer']                         刪除

print '/nThere are %d contacts in the address-book/n' % len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)

if 'Guido' in ab: # OR ab.has_key('Guido')
    print "/nGuido's address is %s" % ab['Guido']

4.5   序列

列表、元組和字符串都是序列,

索引同樣可以是負數,在那樣的情況下,位置是從序列尾開始計算的。

因此,shoplist[-1]表示序列的最後一個元素shoplist[-2]抓取序列的倒數第二個項目

name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

注意,返回的序列從開始位置 開始 ,剛好在 結束 位置之前結束。即開始位置是包含在序列切片中的,而結束位置被排斥在切片外

for i in range(1, 5):
    print i
else:
    print 'The for loop is over'

 

range(1,5)給出序列[1, 2, 3, 4]

 

如果我們爲range提供第三個數,那麼它將成爲步長。例如,range(1,5,2)給出[1,3]

4.6   列表引用與 複製

shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist               引用

mylist = shoplist[:] # make a copy by doing a full slice   複製

4.7   字符串

name = 'Swaroop' # This is a string object

if name.startswith('Swa'):
    print 'Yes, the string starts with "Swa"'

if 'a' in name:
    print 'Yes, it contains the string "a"'

if name.find('war') != -1:
    print 'Yes, it contains the string "war"'

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)   

  最後一行結果: Brazil_*_Russia_*_India_*_China

4.8   DocStrings

def printMax(x, y):
    '''Prints the maximum of two numbers.

    The two values must be integers.'''

    x = int(x) # convert to integers, if possible
    y = int(y)

    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'

printMax(3, 5)
print printMax.__doc__

 

輸出:

5 is maximum
Prints the maximum of two numbers.

        The two values must be integers.

5         使用類

5.1   成員函數

類中的函數 第一個參數都是self

class Person:
    def __init__(self, name):
        self.name = name

    def sayHi(self):
        print 'Hello, my name is', self.name

p = Person('Swaroop')
成員函數中的第一個變量 self 當前類 那個對象   相當於 this

__init__  這個名稱的開始和結尾都是雙下劃線  構造函數

__del__       析夠函數

     當對象不再被使用時,__del__方法運行,但是很難保證這個方法究竟在 什麼時候行。如果你想要指明它的運行,你就得使用del語句,就如同我們在以前的例子中使用的那樣

5.2   成員變量

有兩種類型的 ——類的變量(靜態變量)和對象的變量,

它們根據是類還是對象 擁有 這個變量而區分

類的變量(相當於靜態變量):    在類中用類名.變量 應用    需要先定義

                                 C++成員變量定義位置初始化

對象的變量: 在類中用 self.變量  使用

             在成員函數中 直接用self 引用 ,不需要先定義

能使用self變量來參考同一個對象的變量和方法。這被稱爲 屬性參考

5.3   公共變量與私有變量

      Python中所有的類成員(包括數據成員)都是 公共 ,所有的方法都是 有效的,如果你使用的數據成員名稱以 雙下劃線前綴 比如__privatevarPython的名稱管理體系會有效地把它作爲私有變量

 

6         繼承

   爲了使用繼承,我們把基本類的名稱作爲一個元組跟在定義類時的類名稱之後。然後,我們注意到基本類的__init__方法專門使用self變量調用,這樣我們就可以初始化對象的基本類部分。這一點十分重要——Python不會自動調用基本類的constructor,你得親自專門調用它。

     如果在繼承元組中列了一個以上的類,那麼它就被稱作 多重繼承

class SchoolMember:

        pass

class Teacher(SchoolMember):

     pass

 

 

7         文件操作

7.1   讀一般文件

poem = '''/
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''


f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()

    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file

7.2   INI文件

import ConfigParser

 

filename=’c:my.ini’

config = ConfigParser.ConfigParser()

config.readfp(open(fileName))   

execTimes = config.get("GLOBAL_CONFIG", "execTimes")

 

 

8         持久化對象-儲存器

     Python提供一個標準的模塊,稱爲pickle。使用它你可以在一個文件中儲存任何Python對象,之後你又可以把它完整無缺地取出來。這被稱爲 持久地 儲存對象

     還有另一個模塊稱爲cPickle,它的功能和pickle模塊完全相同,只不過它是用C語言編寫的,因此要快得多(比pickle1000倍)。

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file

f.close()

del shoplist # remove the shoplist

# Read back from the storage

f = file(shoplistfile)
storedlist = p.load(f)

print storedlist

調用儲存器模塊的dump函數,把對象儲存到打開的文件中。這個過程稱爲 儲存

接下來,我們使用pickle模塊的load函數的返回來取回對象。這個過程稱爲 取儲存

 

9         異常

如果某個錯誤或異常沒有被處理,默認的Python處理器就會被調用。它會終止程序的運行,並且打印一個消息,我們已經看到了這樣的處理。

import sys

try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '/nWhy did you do an EOF on me?'
    sys.exit() # exit the program
except:
    print '/nSome error/exception occurred.'
    # here, we are not exiting the program

print 'Done'

 

引發異常

你可以使用raise語句 引發 異常。你還得指明錯誤/異常的名稱和伴隨異常 觸發的 異常對象。你可以引發的錯誤或異常應該分別是一個ErrorException類的直接或間接導出類。

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast


try:
    s = raw_input('Enter something --> ')

    if len(s) < 3:
        raise ShortInputException(len(s), 3)

    # Other work can continue as usual here
except EOFError:
    print '/nWhy did you do an EOF on me?'
except ShortInputException, x:           異常類,異常變量
    print 'ShortInputException: The input was of length %d, /
          was expecting at least %d' % (x.length, x.atleast)

else:
    print 'No exception was raised.'

finally:

pass

10    os模塊

這個模塊包含普遍的操作系統功能。如果你希望你的程序能夠與平臺無關的話,這個模塊是尤爲重要的。即它允許一個程序在編寫後不需要任何改動,也不會發生任何問題,就可以在LinuxWindows下運行。一個例子就是使用os.sep可以取代操作系統特定的路徑分割符。

下面列出了一些在os模塊中比較有用的部分。它們中的大多數都簡單明瞭。

·         os.name字符串指示你正在使用的平臺。比如對於Windows,它是'nt',而對於Linux/Unix用戶,它是'posix'

·         os.getcwd()函數得到當前工作目錄,即當前Python腳本工作的目錄路徑

·         os.getenv()os.putenv()函數分別用來讀取和設置環境變量

·         os.listdir()返回指定目錄下的所有文件和目錄名

·         os.remove()函數用來刪除一個文件。

·         os.system()函數用來運行shell命令。

·         os.linesep字符串給出當前平臺使用的行終止符。例如,Windows使用'/r/n'Linux使用'/n'Mac使用'/r'

·         os.path.split()函數返回一個路徑的目錄名和文件名

·         os.path.isfile()os.path.isdir()函數分別檢驗給出的路徑是一個文件還是目錄。類似地,os.path.existe()函數用來檢驗給出的路徑是否真地存在。

你可以利用Python標準文檔去探索更多有關這些函數和變量的詳細知識。你也可以使用help(sys)等等。

11    其他

11.1       特殊的方法

__init__(self,...)

這個方法在新建對象恰好要被返回使用之前被調用。

__del__(self)

恰好在對象要被刪除之前調用。

__str__(self)

在我們對對象使用print語句或是使用str()的時候調用

__lt__(self,other)

當使用 小於 運算符(<)的時候調用。類似地,對於所有的運算符(+>等等)都有特殊的方法。

__getitem__(self,key)

使用x[key]索引操作符的時候調用。

__len__(self)

對序列對象使用內建的len()函數的時候調用。

 

11.2       lambda形式

lambda語句被用來創建新的函數對象,並且在運行時返回它們。

11.3       execeval語句

exec語句用來執行儲存在字符串或文件中的Python語句。例如,我們可以在運行時生成一個包含Python代碼的字符串,然後使用exec語句執行這些語句。下面是一個簡單的例子。

>>> exec 'print "Hello World"'

Hello World

eval語句用來計算存儲在字符串中的有效Python表達式。下面是一個簡單的例子。

>>> eval('2*3')
6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章