前言
《編寫高質(zhì)量python代碼的59個(gè)有效方法》這本書分類逐條地介紹了編寫python代碼的有效思路和方法,對(duì)理解python和提高編程效率有一定的幫助。本筆記簡(jiǎn)要整理其中的重要方法。
承接上文http://www.itdecent.cn/p/15a6050220e6
http://www.itdecent.cn/p/1f6a2b3b502e
元類與屬性 http://www.itdecent.cn/p/1b1f3a0e87aa
并發(fā)及并行:http://www.itdecent.cn/p/60ad9066d4b6
http://www.itdecent.cn/p/60ad9066d4b6
本次分享書中最后兩章:關(guān)于協(xié)作開發(fā)和部署
7. 協(xié)作開發(fā)
編寫文檔字符串 docstring
Python為文檔提供了內(nèi)置的支持,使得開發(fā)者可以把文檔于代碼塊關(guān)聯(lián)起來(lái)。 能夠在程序運(yùn)行時(shí)之間訪問(wèn)源代碼中的文檔信息。
"""
This is the description of this object
"""
def __init__(self):
self.count=1
def train(self):
print('basemodel')
print(self.count)
pass
def test(self):
pass
class Model(Basemodel):
def __init__(self):
super().__init__()
self.count=2
# def train(self):
# print(self.count)
print(repr(Basemodel.__doc__))
例如這個(gè)例子,可以直接通過(guò)repr()來(lái)獲取類的doc即文檔信息。在編寫文檔字符串時(shí),應(yīng)該遵守相關(guān)規(guī)范(PEP 257):
為模塊編寫文檔: 作為源文件的第一語(yǔ)句,使用三重雙引號(hào)括起來(lái); 描述本模塊的用途,介紹本模塊的相關(guān)操作,強(qiáng)調(diào)本模塊比較重要的類和函數(shù),以便于開發(fā)者能夠了解該模塊的用法
為類編寫文檔 一段話闡述本類的用途,詳述類的操作方式
為函數(shù)編寫文檔 一句話描述本函數(shù)的功能,然后一段話描述具體行為和參數(shù)及輸出
用虛擬環(huán)境隔離項(xiàng)目,重建依賴關(guān)系
通過(guò)pyvenv的工具構(gòu)建虛擬環(huán)境,方便創(chuàng)建版本不同/內(nèi)部軟件包不同的環(huán)境
8. 部署
用模塊級(jí)別的代碼來(lái)配置不同的部署環(huán)境
可以根據(jù)不同的部署環(huán)境(生產(chǎn)/測(cè)試),覆寫程序中的某些部分,根據(jù)環(huán)境不同提供不同的功能,如下例所示

repr字符串輸出調(diào)試信息
print函數(shù)往往無(wú)法清晰地展示數(shù)據(jù)的類型,在調(diào)試程序時(shí)往往需要知道具體的類型,可以使用內(nèi)置的repr來(lái)返回可打印的表示形式,

class Basemodel(object):
"""
This is the description of this object
"""
def __init__(self):
self.count=1
def train(self):
print('basemodel')
print(self.count)
pass
def test(self):
pass
def __repr__(self):
return 'test'#self.__dict__#['count']
t=Basemodel()
print(t)
用unittest測(cè)試全部代碼
Python沒有靜態(tài)類型檢查機(jī)制,編譯器無(wú)法保證程序在運(yùn)行時(shí)一定正確執(zhí)行。Python的動(dòng)態(tài)特性,阻礙了靜態(tài)類型檢查;此外也能方便開發(fā)者為代碼編寫測(cè)試。可以使用內(nèi)置的unittest模塊
def to_str(data):
if isinstance(data,str):
return data
elif isinstance(data,bytes):
return data.decode('utf-8')
else:
raise TypeError('Must supply str or bytes, found : %r'%data)
class UtilsTestCase(TestCase):
def test_to_str_bytes(self):
self.assertEqual('hello',to_str(b'hello'))
UtilsTestCase().test_to_str_bytes(
pdb交互調(diào)試
內(nèi)置的交互調(diào)試器pdb,可以查看程序狀態(tài)、打印局部變量,按照步進(jìn)的方式執(zhí)行程序中的每一個(gè)語(yǔ)句。
在需要調(diào)試的地方加上這調(diào)試命令,相當(dāng)于打斷點(diǎn)。
def test_example():
for i in range(10):
import pdb
pdb.set_trace()
print(i)
test_example()
具體的交互調(diào)試指令包括: step/next/return/continue等
性能分析
Python提供內(nèi)置的性能分析工具: profiler,并將獲取的性能數(shù)據(jù)通過(guò)內(nèi)置的pstats模塊對(duì)數(shù)據(jù)進(jìn)行統(tǒng)計(jì)分析,對(duì)性能分析數(shù)據(jù)進(jìn)行篩選和排序,提取關(guān)鍵的執(zhí)行時(shí)長(zhǎng)信息:
from pstats import Stats
def func(m,n):
a=b=result=1
minNI=min(n,m-n)
for j in range(0,minNI):
a=a*(m-j)
b=b*(minNI-j)
result=a//b
return result
profiler=Profile()
profiler.runcall(lambda : func(152324,27343))
stats=Stats(profiler)
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.print_stats()
stats.print_callers()
因此在對(duì)python程序優(yōu)化前,最好先利用profile對(duì)程序做初步的性能分析
用tracemalloc掌握內(nèi)存使用及泄露情況
Python可以使用內(nèi)置的gc模塊,可以找到當(dāng)前垃圾收集器所集的所有對(duì)象,

END
本人簡(jiǎn)書所有文章均為原創(chuàng),歡迎轉(zhuǎn)載,請(qǐng)注明文章出處 。百度和CSDN等站皆不可信,搜索請(qǐng)謹(jǐn)慎鑒別。技術(shù)類文章一般都有時(shí)效性,本人習(xí)慣不定期對(duì)自己的筆記/博文進(jìn)行更新,因此請(qǐng)?jiān)L問(wèn)本人簡(jiǎn)書主頁(yè)查看最新信息http://www.itdecent.cn/u/40d14973d97c