作者:麦叔
来源:麦叔编程
加注释无疑是很好的习惯,但是有时候会被滥用。我一直持有以下几个观点:
先来看看什么是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,而不是使用注释吧。
数据分析咨询请扫描二维码
CDA数据分析师在中国航信高科技产业园进行了面向测试度量的数据分析培训课程,培训人数近2 ...
2024-05-01CDA数据分析师走进深圳迈瑞生物医疗电子股份有限公司,在迈瑞总部展开了为期两天的培训,本次课程参训人员线上及线下近百人, ...
2024-05-01CDA数据分析师在合肥市对合肥阳光新能源科技有限公司开展了为期8天的企业内训。 合肥阳光新能源科技 ...
2024-05-01CDA数据分析师走进海尔大学,进行了《数据治理与数据中台建设的道与术》专题培训,培训现场爆满,近百人参加了此次培训。 ...
2024-05-01在中国银行苏州分行培训中心开始数据分析师培训,此次培训课程共10天内容,包括Excel、MySQL、概率论与数理统计、SPSS等内容, ...
2024-05-01从实际的业务需求出发,结合行业的典型应用特点,围绕实际的商业问题,探讨数据挖掘、机器学习模型在金融领域的应用,包括获客、信用评分、细分画像、交叉销售、反欺诈、违规识别、时序预测、运筹优化、流程挖掘九个方面,形成 ...
2024-05-01本次培训课程为线上+线下的模式,由于学员编程能力不一、部分学员没有编程基础,故提供统计学、python基 ...
2024-05-01华夏银行信用卡中心-机器学习培训 1、课程亮点 取材于业界一流企业和顶级咨询公司的行业实践;已经被证明是人人 ...
2024-05-01主 题:数据中台建设及数据分析应用主题分享 1. 数据中台市场洞察 2. 主流数据中台产品比较 3. 某企业数据中 ...
2024-05-01围绕“数据驱动”战略,全力打造我行 300 人数字化人才梯队,着力培养数字化管理人才、大数据专业团队 ...
2024-05-01在当今数据驱动的商业环境中,数据分析成为了企业决策的重要依据。通过对大量数据的收集、处理和分析,企业能够更好地理解市场 ...
2024-04-29在人工智能(AI)的世界里,提示词(Prompt)是一种强大的工具,它能够引导AI按照用户的需求产生特定的输出。本文将深入探讨AI ...
2024-04-29CDA立足未来职场,拓展前沿视野——对外经贸大学保险学院举办“三全育人大讲堂”分享行业最新动态。 ...
2024-04-294月2日,CDA数据分析师创始发起人兼协会理事长赵坚毅博士受邀在浙江万里学院举办了一场以“数字化能力在职场中的作用” ...
2024-04-29随机森林(Random Forests)现在机器学习中比较火的一个算法,是一种基于Bagging的集成学习方法,能够很好地处理分类和回归的问 ...
2022-12-23方差分析是数据分析中常用的一种统计分析方法,接下来让我们简单了解一下方差分析的基本思想和原理吧。 方差分析(Analysis ...
2022-12-23来源:关于数据分析与可视化 关于streamlit-aggrid 数据排序 表格样式的调整 数据 ...
2022-08-03作者:麦叔 定义 「把上面晦涩的概念汇成一句话就是:」 ❝ 回调函数就是一个被作为参 ...
2022-08-03现今,高学历人群日益增多,物以稀为贵的高学历光环淡去。无论本科生还是研究生,甚至博士生,求职竞争力都大不如前,就业压力越来越大。
2022-06-01某家企业10个人面试,有9个本科生……如何脱颖而出,除得体的举止和良好的沟通力外,证书成重要筹码,这也是很多人考证的关键所在。
2022-04-14