京公网安备 11010802034615号
经营许可证编号:京B2-20210330
作者:麦叔
来源:麦叔编程
加注释无疑是很好的习惯,但是有时候会被滥用。我一直持有以下几个观点:
先来看看什么是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
“2026年考什么证含金量高”这个问题,很难用一张榜单回答。同一本证书,对想进会计师事务所的人有价值,对想做行政的人可能用处 ...
2026-10-29一、Tableau 做地图的优势 在所有 BI 工具里,Tableau 的地图能力是第一梯队的。它内置了全球行政区划地理数据库,只要你的数据 ...
2026-10-29一、问题场景:为什么 Excel 自带直方图不支持多组 做数据分析时,经常需要把两组数据的分布放在同一张图里对比——比如"实验组 ...
2026-10-29当下,我们已然步入数据要素价值全面释放的智能时代。数据不再只是零散的数字记录,更是驱动新质生产力运转的核心动能、滋养人工 ...
2026-10-29一、RFM模型概述 RFM模型是由 George Cullinan 提出、营销领域公认的经典客户价值细分模型,依托客户交易行为数据,从三个核心维 ...
2026-10-28“不用学历可以考的资格证”这个说法,实际混着两类情况:一类是证书本身对学历没有硬性要求,报名时只看年龄、身份或培训经历; ...
2026-10-2837岁考什么证,先别急着看“女生适合考什么”的榜单。这个年龄处在职业中期,优势是已有工作经验和行业理解,约束是时间精力有限 ...
2026-10-28一、卡方分布是什么 卡方分布(Chi-square Distribution,χ²分布)是统计学中一种常用的概率分布,它和正态分布、t分布一样, ...
2026-10-28职业证书的作用不能一概而论。它既不是“考了就能找到好工作”的通行证,也不是“花钱买张纸”的摆设。真正决定一张证书有多大用 ...
2026-10-28产品岗没有统一的法定准入证书,招聘时也很少把某张证书写成硬性门槛。所以“真正有用”不能看广告里的名头,而要看三件事:它对 ...
2026-10-28“一般可以考什么证书”很难给出一份通用榜单。同为“证书”,有的是法律规定的准入资格,无证不能上岗;有的是职称评聘参考;有 ...
2026-10-28“现在大学生要什么证书好”,这个问题没有统一答案。同一张证书,对想进银行的学生可能是加分项,对准备考公的学生可能完全用不 ...
2026-10-28“十大证书含金量最高”这类榜单,最大的问题不是排名不准,而是没有交代排名依据。准入类和加分类混在一起排,高壁垒的和低门槛 ...
2026-10-28“什么证容易考且有用”,这个问题本身藏着一个容易踩的坑:把“容易考”和“有用”当成两个独立打分项,各找几个高分证书拼在一 ...
2026-10-28想考一个证书,第一步不是买教材,而是先确认它属于哪一类证书、由谁发证、在哪里报名。考取证书的通用流程可以概括为六步:确定 ...
2026-10-28“女生考什么证”这个问题,网上常见的答案是“教师资格证、会计证、普通话证”,理由往往是“稳定”“适合女孩子”。这类回答的 ...
2026-10-28“女的考什么证书比较实用”这个问题,本身藏着一个容易走偏的前提:把性别当成筛选证书的依据。证书不认性别,岗位也不按性别分 ...
2026-10-28“哪些考试含金量高”这个问题,很难有一张适合所有人的总榜。同一个考试,对想进医院的人和对想做运营的人,价值完全不同。含金 ...
2026-10-28“国家认可的技能证书”日常被用得很宽:有人指职业资格,有人指职业技能等级,也有人把培训结业证、企业认证一并算入。口径不统 ...
2026-10-28工作后考市场营销证书,容易陷入两种极端:要么被“高薪就业”“行业必备”的宣传推着走,要么觉得证书都没用、不如攒经验。更实 ...
2026-10-28