
作者:麥叔
來源:麥叔編程
加注釋無疑是很好的習慣,但是有時候會被濫用。我一直持有以下幾個觀點:
先來看看什么是docstring
所以docstring是注釋,但又不是普通的注釋,可以說它具有一定的語義,可以被python的help()函數或者其他代碼識別。這些都是注釋所不具備的。
要編寫更好的代碼,最好的習慣之一是看內置庫的源代碼。這些代碼通常都是很經典的。
我們來看看random庫的部分源代碼:
class Random(_random.Random): """Random number generator base class used by bound module functions.
Used to instantiate instances of Random to get generators that don't
share state.
Class Random can also be subclassed if you want to use a different basic
generator of your own devising: in that case, override the following
methods: random(), seed(), getstate(), and setstate().
Optionally, implement a getrandbits() method so that randrange()
can cover arbitrarily large ranges.
""" VERSION = 3 # used by getstate/setstate def __init__(self, x=None): """Initialize an instance.
Optional argument x controls seeding, as for Random.seed().
""" self.seed(x)
self.gauss_next = None def seed(self, a=None, version=2): """Initialize internal state from a seed.
The only supported seed types are None, int, float,
str, bytes, and bytearray.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If *a* is an int, all bits are used.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
""" if version == 1 and isinstance(a, (str, bytes)):
a = a.decode('latin-1') if isinstance(a, bytes) else a
x = ord(a[0]) << 7 if a else 0 for c in map(ord, a):
x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF x ^= len(a)
a = -2 if x == -1 else x elif version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str):
a = a.encode()
a = int.from_bytes(a + _sha512(a).digest(), 'big') elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)):
_warn('Seeding based on hashing is deprecatedn' 'since Python 3.9 and will be removed in a subsequent ' 'version. The only n' 'supported seed types are: None, ' 'int, float, str, bytes, and bytearray.',
DeprecationWarning, 2)
super().seed(a)
self.gauss_next = None def getstate(self): """Return internal state; can be passed to setstate() later.""" return self.VERSION, super().getstate(), self.gauss_next def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3:
version, internalstate, self.gauss_next = state
super().setstate(internalstate) elif version == 2:
version, internalstate, self.gauss_next = state # In version 2, the state was saved as signed ints, which causes # inconsistencies between 32/64-bit systems. The state is # really unsigned 32-bit ints, so we convert negative ints from # version 2 to positive longs for version 3. try:
internalstate = tuple(x % (2 ** 32) for x in internalstate) except ValueError as e: raise TypeError from e
super().setstate(internalstate) else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" %
(version, self.VERSION))
類的開頭,和方法的開頭都有大段的docstring。
我們來試一下docstring的使用。
打開命令行窗口,進入交互式Python。
如下所示,可以看到,我們寫的docstring自動成為了一個名為__doc__的屬性:
這個屬性任何類或函數都有,只不過有的為空。
>>> import random
>>> random.__doc__
'Random variable generators.nn bytesn -----n uniform bytes (values between 0 and 255)nn integersn --------n uniform within rangenn sequencesn ---------n pick random elementn pick random samplen pick weighted random samplen generate random permutationnn distributions on the real line:n ------------------------------n uniformn triangularn normal (Gaussian)n lognormaln negative exponentialn gamman betan pareton Weibullnn distributions on the circle (angles 0 to 2pi)n ---------------------------------------------n circular uniformn von MisesnnGeneral notes on the underlying Mersenne Twister core generator:nn* The period is 2**19937-1.n* It is one of the most extensively tested generators in existence.n* The random() method is implemented in C, executes in a single Python step,n and is, therefore, threadsafe.nn'
docstring的第二個用法是,可以用help()函數打印出來。如下所示:
Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:19) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> help(random)
這時候屏幕就會展示random模塊的docstring,這正是上面代碼中的三引號括起來的那一大段:
普通青年寫注釋,文藝青年用docstring。下一次寫類,寫函數的時候,嘗試使用docstring,而不是使用注釋吧。
數據分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
CDA數據分析師證書考試體系(更新于2025年05月22日)
2025-05-26解碼數據基因:從數字敏感度到邏輯思維 每當看到超市貨架上商品的排列變化,你是否會聯想到背后的銷售數據波動?三年前在零售行 ...
2025-05-23在本文中,我們將探討 AI 為何能夠加速數據分析、如何在每個步驟中實現數據分析自動化以及使用哪些工具。 數據分析中的AI是什么 ...
2025-05-20當數據遇見人生:我的第一個分析項目 記得三年前接手第一個數據分析項目時,我面對Excel里密密麻麻的銷售數據手足無措。那些跳動 ...
2025-05-20在數字化運營的時代,企業每天都在產生海量數據:用戶點擊行為、商品銷售記錄、廣告投放反饋…… 這些數據就像散落的拼圖,而相 ...
2025-05-19在當今數字化營銷時代,小紅書作為國內領先的社交電商平臺,其銷售數據蘊含著巨大的商業價值。通過對小紅書銷售數據的深入分析, ...
2025-05-16Excel作為最常用的數據分析工具,有沒有什么工具可以幫助我們快速地使用excel表格,只要輕松幾步甚至輸入幾項指令就能搞定呢? ...
2025-05-15數據,如同無形的燃料,驅動著現代社會的運轉。從全球互聯網用戶每天產生的2.5億TB數據,到制造業的傳感器、金融交易 ...
2025-05-15大數據是什么_數據分析師培訓 其實,現在的大數據指的并不僅僅是海量數據,更準確而言是對大數據分析的方法。傳統的數 ...
2025-05-14CDA持證人簡介: 萬木,CDA L1持證人,某電商中廠BI工程師 ,5年數據經驗1年BI內訓師,高級數據分析師,擁有豐富的行業經驗。 ...
2025-05-13CDA持證人簡介: 王明月 ,CDA 數據分析師二級持證人,2年數據產品工作經驗,管理學博士在讀。 學習入口:https://edu.cda.cn/g ...
2025-05-12CDA持證人簡介: 楊貞璽 ,CDA一級持證人,鄭州大學情報學碩士研究生,某上市公司數據分析師。 學習入口:https://edu.cda.cn/g ...
2025-05-09CDA持證人簡介 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度、美團、阿里等 ...
2025-05-07相信很多做數據分析的小伙伴,都接到過一些高階的數據分析需求,實現的過程需要用到一些數據獲取,數據清洗轉換,建模方法等,這 ...
2025-05-06以下的文章內容來源于劉靜老師的專欄,如果您想閱讀專欄《10大業務分析模型突破業務瓶頸》,點擊下方鏈接 https://edu.cda.cn/g ...
2025-04-30CDA持證人簡介: 邱立峰 CDA 數據分析師二級持證人,數字化轉型專家,數據治理專家,高級數據分析師,擁有豐富的行業經驗。 ...
2025-04-29CDA持證人簡介: 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度,美團,阿里等 ...
2025-04-28CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-27數據分析在當今信息時代發揮著重要作用。單因素方差分析(One-Way ANOVA)是一種關鍵的統計方法,用于比較三個或更多獨立樣本組 ...
2025-04-25CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-25