高效且優雅的 編寫Python 代碼

wqqzlm 8年前發布 | 11K 次閱讀 Python Python開發

Python 作為一門入門極易并容易上癮的語音,相信已經成為了很多人 “寫著玩” 的標配腳本語言。但很多教材并沒有教授 Python 的進階和優化。本文作為進階系列的文章,從基礎的語法到函數、迭代器、類,還有之后系列的線程 / 進程、第三方庫、網絡編程等內容,共同學習如何寫出更加 Pythonic 的代碼部分提煉自書籍:《Effective Python》&《Python3 Cookbook》,但也做出了修改,并加上了我自己的理解和運用中的最佳實踐

Pythonic

列表切割

list[start:end:step]

  • 如果從列表開頭開始切割,那么忽略 start 位的 0,例如 list[:4]
  • 如果一直切到列表尾部,則忽略 end 位的 0,例如 list[3:]
  • 切割列表時,即便 start 或者 end 索引跨界也不會有問題
  • 列表切片不會改變原列表。索引都留空時,會生成一份原列表的拷貝
b = a[:]
assert b == a and b is not a # true

列表推導式

  • 使用列表推導式來取代 map 和 filter
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# use map
squares = map(lambda x: x ** 2, a)
# use list comprehension
squares = [x ** 2 for x in a]
# 一個很大的好處是,列表推導式可以對值進行判斷,比如
squares = [x ** 2 for x in a if x % 2 == 0]
# 而如果這種情況要用 map 或者 filter 方法實現的話,則要多寫一些函數
  • 不要使用含有兩個以上表達式的列表推導式
# 有一個嵌套的列表,現在要把它里面的所有元素扁平化輸出
list = [[
  [1, 2, 3],
  [4, 5, 6]
]]
# 使用列表推導式
flat_list = [x for list0in listfor list1in list0for x in list1]
# [1, 2, 3, 4, 5, 6]
 
# 可讀性太差,易出錯。這種時候更建議使用普通的循環
flat_list = []
for list0in list:
    for list1in list0:
        flat_list.extend(list1)
  • 數據多時,列表推導式可能會消耗大量內存,此時建議使用生成器表達式
# 在列表推導式的推導過程中,對于輸入序列的每個值來說,都可能要創建僅含一項元素的全新列表。因此數據量大時很耗性能。
# 使用生成器表達式
list = (x ** 2 for x in range(0, 1000000000))
# 生成器表達式返回的迭代器,只有在每次調用時才生成值,從而避免了內存占用

迭代

  • 需要獲取 index 時使用 enumerate
  • enumerate 可以接受第二個參數,作為迭代時加在 index 上的數值
list = ['a', 'b', 'c', 'd']
 
for index, valuein enumerate(list):
    print(index)
# 0
# 1
# 2
# 3
 
for index, valuein enumerate(list, 2):
    print(index)
# 2
# 3
# 4
# 5
  • 用 zip 同時遍歷兩個迭代器
list_a = ['a', 'b', 'c', 'd']
list_b = [1, 2, 3]
# 雖然列表長度不一樣,但只要有一個列表耗盡,則迭代就會停止
for letter, numberin zip(list_a, list_b):
    print(letter, number)
# a 1
# b 2
# c 3
  • zip 遍歷時返回一個元組
a = [1, 2, 3]
b = ['w', 'x', 'y', 'z']
for i in zip(a,b):
    print(i)
 
# (1, 'w')
# (2, 'x')
# (3, 'y')
  • 關于 for 和 while 循環后的 else 塊
    • 循環 正常結束 之后會調用 else 內的代碼
    • 循環里通過 break 跳出循環,則不會執行 else
    • 要遍歷的序列為空時,立即執行 else
for i in range(2):
    print(i)
else:
    print('loop finish')
# 0
# 1
# loop finish
 
for i in range(2):
    print(i)
    if i % 2 == 0:
        break
else:
    print('loop finish')
# 0

反向迭代

對于普通的序列(列表),我們可以通過內置的 reversed() 函數進行反向迭代:

list_example = [i for i in range(5)]
iter_example = (i for i in range(5)) # 迭代器
set_example = {i for i in range(5)} # 集合
 
# 普通的正向迭代
# for i in list_example
 
# 通過 reversed 進行反向迭代
for i in reversed(list_example):
    print(i)
# 4
# 3
# 2
# 1
# 0
 
# 但無法作用于 集合 和 迭代器
reversed(iter_example) # TypeError: argument to reversed() must be a sequence

除此以外,還可以通過實現類里的 __reversed__ 方法,將類進行反向迭代:

class Countdown:
    def __init__(self, start):
        self.start = start
 
    # 正向迭代
    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1
 
    # 反向迭代
    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1
 
for i in reversed(Countdown(4)):
    print(i)
# 1
# 2
# 3
# 4
for i in Countdown(4):
    print(i)
# 4
# 3
# 2
# 1

try/except/else/finally

  • 如果 try 內沒有發生異常,則調用 else 內的代碼
  • else 會在 finally 之前運行
  • 最終一定會執行 finally ,可以在其中進行清理工作

函數

使用裝飾器

裝飾器用于在不改變原函數代碼的情況下修改已存在的函數。常見場景是增加一句調試,或者為已有的函數增加 log 監控

舉個栗子:

defdecorator_fun(fun):
    defnew_fun(*args, **kwargs):
        print('current fun:', fun.__name__)
        print('position arguments:', args)
        print('key arguments:', **kwargs)
        result = fun(*args, **kwargs)
        print(result)
        return result
    return new_fun
    
@decorator_fun
defadd(a, b):
    return a + b
 
add(3, 2)
# current fun: add
# position arguments: (3, 2)
# key arguments: {}
# 5

除此以外,還可以編寫接收參數的裝飾器,其實就是在原本的裝飾器上的外層又嵌套了一個函數:

defread_file(filename='results.txt'):
    defdecorator_fun(fun):
        defnew_fun(*args, **kwargs):
            result = fun(*args, **kwargs)
            withopen(filename, 'a') as f:
                f.write(result + '\n')
            return result
        return new_fun
    return decorator_fun
 
# 使用裝飾器時代入參數
@read_file(filename='log.txt')
defadd(a, b):
    return a + b

但是像上面那樣使用裝飾器的話有一個問題:

@decorator_fun
defadd(a, b):
    return a + b
 
print(add.__name__)
# new_fun

也就是說原函數已經被裝飾器里的 new_fun 函數替代掉了。調用經過裝飾的函數,相當于調用一個新函數。查看原函數的參數、注釋、甚至函數名的時候,只能看到裝飾器的相關信息。為了解決這個問題,我們可以使用 Python 自帶的 functools.wraps 方法。

functools.wraps 是個很 hack 的方法,它本事作為一個裝飾器,做用在裝飾器內部將要返回的函數上。也就是說,它是裝飾器的裝飾器,并且以原函數為參數,作用是保留原函數的各種信息,使得我們之后查看被裝飾了的原函數的信息時,可以保持跟原函數一模一樣。

fromfunctoolsimportwraps
 
defdecorator_fun(fun):
    @wraps(fun)
    defnew_fun(*args, **kwargs):
        result = fun(*args, **kwargs)
        print(result)
        return result
    return new_fun
    
@decorator_fun
defadd(a, b):
    return a + b
 
print(add.__name__)
# add

此外,有時候我們的裝飾器里可能會干不止一個事情,此時應該把事件作為額外的函數分離出去。但是又因為它可能僅僅和該裝飾器有關,所以此時可以構造一個裝飾器類。原理很簡單,主要就是編寫類里的 __call__ 方法,使類能夠像函數一樣的調用。

fromfunctoolsimportwraps
 
class logResult(object):
    def__init__(self, filename='results.txt'):
        self.filename = filename
    
    def__call__(self, fun):
        @wraps(fun)
        defnew_fun(*args, **kwargs):
            result = fun(*args, **kwargs)
            withopen(filename, 'a') as f:
                f.write(result + '\n')
            return result
        self.send_notification()
        return new_fun
    
    defsend_notification(self):
        pass
 
@logResult('log.txt')
defadd(a, b):
    return a + b

使用生成器

考慮使用生成器來改寫直接返回列表的函數

# 定義一個函數,其作用是檢測字符串里所有 a 的索引位置,最終返回所有 index 組成的數組
defget_a_indexs(string):
    result = []
    for index, letterin enumerate(string):
        if letter == 'a':
            result.append(index)
    return result

用這種方法有幾個小問題:

  • 每次獲取到符合條件的結果,都要調用 append 方法。但實際上我們的關注點根本不在這個方法,它只是我們達成目的的手段,實際上只需要 index 就好了
  • 返回的 result 可以繼續優化
  • 數據都存在 result 里面,如果數據量很大的話,會比較占用內存

因此,使用生成器 generator 會更好。生成器是使用 yield 表達式的函數,調用生成器時,它不會真的執行,而是返回一個迭代器,每次在迭代器上調用內置的 next 函數時,迭代器會把生成器推進到下一個 yield 表達式:

defget_a_indexs(string):
    for index, letterin enumerate(string):
        if letter == 'a':
            yieldindex

獲取到一個生成器以后,可以正常的遍歷它:

string = 'this is a test to find a\' index'
indexs = get_a_indexs(string)
 
# 可以這樣遍歷
for i in indexs:
    print(i)
 
# 或者這樣
try:
    while True:
        print(next(indexs))
exceptStopIteration:
    print('finish!')
 
# 生成器在獲取完之后如果繼續通過 next() 取值,則會觸發 StopIteration 錯誤
# 但通過 for 循環遍歷時會自動捕獲到這個錯誤

如果你還是需要一個列表,那么可以將函數的調用結果作為參數,再調用 list 方法

results = get_a_indexs('this is a test to check a')
results_list = list(results)

可迭代對象

需要注意的是,普通的迭代器只能迭代一輪,一輪之后重復調用是無效的。解決這種問題的方法是,你可以 定義一個可迭代的容器類

class LoopIter(object):
    def__init__(self, data):
        self.data = data
    # 必須在 __iter__ 中 yield 結果
    def__iter__(self):
        for index, letterin enumerate(self.data):
            if letter == 'a':
                yieldindex

這樣的話,將類的實例迭代重復多少次都沒問題:

string = 'this is a test to find a\' index'
indexs = LoopIter(string)
 
print('loop 1')
for _ in indexs:
    print(_)
# loop 1
# 8
# 23
 
print('loop 2')
for _ in indexs:
    print(_)
# loop 2
# 8
# 23

但要注意的是,僅僅是實現 __iter__ 方法的迭代器,只能通過 for 循環來迭代;想要通過 next 方法迭代的話則需要使用 iter 方法:

string = 'this is a test to find a\' index'
indexs = LoopIter(string)
 
next(indexs) # TypeError: 'LoopIter' object is not an iterator
 
iter_indexs = iter(indexs)
next(iter_indexs) # 8

使用位置參數

有時候,方法接收的參數數目可能不一定,比如定義一個求和的方法,至少要接收兩個參數:

defsum(a, b):
    return a + b
 
# 正常使用
sum(1, 2) # 3
# 但如果我想求很多數的總和,而將參數全部代入是會報錯的,而一次一次代入又太麻煩
sum(1, 2, 3, 4, 5) # sum() takes 2 positional arguments but 5 were given

對于這種接收參數數目不一定,而且不在乎參數傳入順序的函數,則應該利用位置參數 *args :

defsum(*args):
    result = 0
    for numin args:
        result += num
    return result
 
sum(1, 2) # 3
sum(1, 2, 3, 4, 5) # 15
# 同時,也可以直接把一個數組帶入,在帶入時使用 * 進行解構
sum(*[1, 2, 3, 4, 5]) # 15

但要注意的是,不定長度的參數 args 在傳遞給函數時,需要先轉換成元組 tuple 。這意味著,如果你將一個生成器作為參數帶入到函數中,生成器將會先遍歷一遍,轉換為元組。這可能會消耗大量內存:

defget_nums():
    for numin range(10):
        yieldnum
 
nums = get_nums()
sum(*nums) # 45
# 但在需要遍歷的數目較多時,會占用大量內存

使用關鍵字參數

  • 關鍵字參數可提高代碼可讀性
  • 可以通過關鍵字參數給函數提供默認值
  • 便于擴充函數參數

定義只能使用關鍵字參數的函數

  • 普通的方式,在調用時不會強制要求使用關鍵字參數
# 定義一個方法,它的作用是遍歷一個數組,找出等于(或不等于)目標元素的 index
defget_indexs(array, target='', judge=True):
    for index, itemin enumerate(array):
        if judgeand item == target:
            yieldindex
        elifnot judgeand item != target:
            yieldindex
 
array = [1, 2, 3, 4, 1]
# 下面這些都是可行的
result = get_indexs(array, target=1, judge=True)
print(list(result)) # [0, 4]
result = get_indexs(array, 1, True)
print(list(result)) # [0, 4]
result = get_indexs(array, 1)
print(list(result)) # [0, 4]
  • 使用 Python3 中強制關鍵字參數的方式
# 定義一個方法,它的作用是遍歷一個數組,找出等于(或不等于)目標元素的 index
defget_indexs(array, *, target='', judge=True):
    for index, itemin enumerate(array):
        if judgeand item == target:
            yieldindex
        elifnot judgeand item != target:
            yieldindex
 
array = [1, 2, 3, 4, 1]
# 這樣可行
result = get_indexs(array, target=1, judge=True)
print(list(result)) # [0, 4]
# 也可以忽略有默認值的參數
result = get_indexs(array, target=1)
print(list(result)) # [0, 4]
# 但不指定關鍵字參數則報錯
get_indexs(array, 1, True)
# TypeError: get_indexs() takes 1 positional argument but 3 were given
  • 使用 Python2 中強制關鍵字參數的方式
# 定義一個方法,它的作用是遍歷一個數組,找出等于(或不等于)目標元素的 index
# 使用 **kwargs,代表接收關鍵字參數,函數內的 kwargs 則是一個字典,傳入的關鍵字參數作為鍵值對的形式存在
defget_indexs(array, **kwargs):
    target = kwargs.pop('target', '')
    judge = kwargs.pop('judge', True)
    for index, itemin enumerate(array):
        if judgeand item == target:
            yieldindex
        elifnot judgeand item != target:
            yieldindex
 
array = [1, 2, 3, 4, 1]
# 這樣可行
result = get_indexs(array, target=1, judge=True)
print(list(result)) # [0, 4]
# 也可以忽略有默認值的參數
result = get_indexs(array, target=1)
print(list(result)) # [0, 4]
# 但不指定關鍵字參數則報錯
get_indexs(array, 1, True)
# TypeError: get_indexs() takes 1 positional argument but 3 were given

關于參數的默認值

算是老生常談了: 函數的默認值只會在程序加載模塊并讀取到該函數的定義時設置一次

也就是說,如果給某參數賦予動態的值( 比如 [] 或者 {} ),則如果之后在調用函數的時候給參數賦予了其他參數,則以后再調用這個函數的時候,之前定義的默認值將會改變,成為上一次調用時賦予的值:

defget_default(value=[]):
    return value
    
result = get_default()
result.append(1)
result2 = get_default()
result2.append(2)
print(result) # [1, 2]
print(result2) # [1, 2]

因此,更推薦使用 None 作為默認參數,在函數內進行判斷之后賦值:

defget_default(value=None):
    if valueis None:
        return []
    return value
    
result = get_default()
result.append(1)
result2 = get_default()
result2.append(2)
print(result) # [1]
print(result2) # [2]

__slots__

默認情況下,Python 用一個字典來保存一個對象的實例屬性。這使得我們可以在運行的時候動態的給類的實例添加新的屬性:

test = Test()
test.new_key = 'new_value'

然而這個字典浪費了多余的空間 — 很多時候我們不會創建那么多的屬性。因此通過 __slots__ 可以告訴 Python 不要使用字典而是固定集合來分配空間。

class Test(object):
    # 用列表羅列所有的屬性
    __slots__ = ['name', 'value']
    def__init__(self, name='test', value='0'):
        self.name = name
        self.value = value
 
test = Test()
# 此時再增加新的屬性則會報錯
test.new_key = 'new_value'
# AttributeError: 'Test' object has no attribute 'new_key'

__call__

通過定義類中的 __call__ 方法,可以使該類的實例能夠像普通函數一樣調用。

class AddNumber(object):
    def__init__(self):
        self.num = 0
 
    def__call__(self, num=1):
        self.num += num
 
add_number = AddNumber()
print(add_number.num) # 0
add_number() # 像方法一樣的調用
print(add_number.num) # 1
add_number(3)
print(add_number.num) # 4

通過這種方式實現的好處是,可以通過類的屬性來保存狀態,而不必創建一個閉包或者全局變量。

@classmethod & @staticmethod

@classmethod 和 @staticmethod 很像,但他們的使用場景并不一樣。

  • 類內部普通的方法,都是以 self 作為第一個參數,代表著通過實例調用時,將實例的作用域傳入方法內;
  • @classmethod 以 cls 作為第一個參數,代表將類本身的作用域傳入。無論通過類來調用,還是通過類的實例調用,默認傳入的第一個參數都將是類本身
  • @staticmethod 不需要傳入默認參數,類似于一個普通的函數

來通過實例了解它們的使用場景:

假設我們需要創建一個名為 Date 的類,用于儲存 年/月/日 三個數據

class Date(object):
    def__init__(self, year=0, month=0, day=0):
        self.year = year
        self.month = month
        self.day = day
    
    @property
    deftime(self):
        return "{year}-{month}-{day}".format(
            year=self.year,
            month=self.month,
            day=self.day
        )

上述代碼創建了 Date 類,該類會在初始化時設置 day/month/year 屬性,并且通過 property 設置了一個 getter ,可以在實例化之后,通過 time 獲取存儲的時間:

date = Date('2016', '11', '09')
date.time # 2016-11-09

但如果我們想改變屬性傳入的方式呢?畢竟,在初始化時就要傳入年/月/日三個屬性還是很煩人的。能否找到一個方法,在不改變現有接口和方法的情況下,可以通過傳入 2016-11-09 這樣的字符串來創建一個 Date 實例?

你可能會想到這樣的方法:

date_string = '2016-11-09'
year, month, day = map(str, date_string.split('-'))
date = Date(year, month, day)

但不夠好:

  • 在類外額外多寫了一個方法,每次還得格式化以后獲取參數
  • 這個方法也只跟 Date 類有關
  • 沒有解決傳入參數過多的問題

此時就可以利用 @classmethod ,在類的內部新建一個格式化字符串,并返回類的實例的方法:

# 在 Date 內新增一個 classmethod
@classmethod
deffrom_string(cls, string):
    year, month, day = map(str, string.split('-'))
    # 在 classmethod 內可以通過 cls 來調用到類的方法,甚至創建實例
    date = cls(year, month, day)
    return date

這樣,我們就可以通過 Date 類來調用 from_string 方法創建實例,并且不侵略、修改舊的實例化方式:

date = Date.from_string('2016-11-09')
# 舊的實例化方式仍可以使用
date_old = Date('2016', '11', '09')

好處:

  • 在 @classmethod 內,可以通過 cls 參數,獲取到跟外部調用類時一樣的便利
  • 可以在其中進一步封裝該方法,提高復用性
  • 更加符合面向對象的編程方式

而 @staticmethod ,因為其本身類似于普通的函數,所以可以把和這個類相關的 helper 方法作為 @staticmethod ,放在類里,然后直接通過類來調用這個方法。

# 在 Date 內新增一個 staticmethod
@staticmethod
def is_month_validate(month):
    return int(month) <= 12 and int(month) >= 1

將與日期相關的輔助類函數作為 @staticmethod 方法放在 Date 類內后,可以通過類來調用這些方法:

month = '08'
if not Date.is_month_validate(month):
    print('{} is a validate month number'.format(month))

創建上下文管理器

上下文管理器,通俗的介紹就是:在代碼塊執行前,先進行準備工作;在代碼塊執行完成后,做收尾的處理工作。 with 語句常伴隨上下文管理器一起出現,經典場景有:

withopen('test.txt', 'r') as file:
    for linein file.readlines():
        print(line)

通過 with 語句,代碼完成了文件打開操作,并在調用結束,或者讀取發生異常時自動關閉文件,即完成了文件讀寫之后的處理工作。如果不通過上下文管理器的話,則會是這樣的代碼:

file = open('test.txt', 'r')
try:
    for linein file.readlines():
        print(line)
finally:
    file.close()

比較繁瑣吧?所以說使用上下文管理器的好處就是,通過調用我們預先設置好的回調,自動幫我們處理代碼塊開始執行和執行完畢時的工作。而通過自定義類的 __enter__ 和 __exit__ 方法,我們可以自定義一個上下文管理器。

class ReadFile(object):
    def__init__(self, filename):
        self.file = open(filename, 'r')
    
    def__enter__(self):
        return self.file
    
    def__exit__(self, type, value, traceback):
        # type, value, traceback 分別代表錯誤的類型、值、追蹤棧
        self.file.close()
        # 返回 True 代表不拋出錯誤
        # 否則錯誤會被 with 語句拋出
        return True

然后可以以這樣的方式進行調用:

withReadFile('test.txt') as file_read:
    for linein file_read.readlines():
        print(line)

在調用的時候:

  1. with 語句先暫存了 ReadFile 類的 __exit__ 方法
  2. 然后調用 ReadFile 類的 __enter__ 方法
  3. __enter__ 方法打開文件,并將結果返回給 with 語句
  4. 上一步的結果被傳遞給 file_read 參數
  5. 在 with 語句內對 file_read 參數進行操作,讀取每一行
  6. 讀取完成之后, with 語句調用之前暫存的 __exit__ 方法
  7. __exit__ 方法關閉了文件

要注意的是,在 __exit__ 方法內,我們關閉了文件,但最后返回 True ,所以錯誤不會被 with 語句拋出。否則 with 語句會拋出一個對應的錯誤。

 

來自:http://python.jobbole.com/86808/

 

 本文由用戶 wqqzlm 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!