热线电话:13121318867

登录
首页精彩阅读普通青年加注释,文艺青年用docstring
普通青年加注释,文艺青年用docstring
2022-03-16
收藏
普通青年加注释,文艺青年用docstring

作者:麦叔

来源:麦叔编程

我对注释的态度

加注释无疑是很好的习惯,但是有时候会被滥用。我一直持有以下几个观点:

  • 最好的注释是代码,把代码写清晰是首要的,是程序员最重要的修炼。
  • 注释应该言简意赅,不是越多越好。修改了代码后,要对注释做相应的修改,否则会给阅读者产生误导。
  • Python的方法总体解释,应该使用docstring,不要使用注释。方法体内必要的地方可以注释。

docstring

先来看看什么是docstring

  • docstring是在类的第一行或者方法的第一行添加的用于解释类或者方法的字符串
  • docstring必须用三引号,可以是单引号,也可以是双引号,但必须是三引号。
  • docstring可以自动生成Python文档,可以使用help()函数查看。

所以docstring是注释,但又不是普通的注释,可以说它具有一定的语义,可以被pythonhelp()函数或者其他代码识别。这些都是注释所不具备的。

看个例子

要编写更好的代码,最好的习惯之一是看内置库的源代码。这些代码通常都是很经典的。

我们来看看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的两个用法:

我们来试一下docstring的使用。

__doc__属性

打开命令行窗口,进入交互式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()函数

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。下一次写类,写函数的时候,尝试使用docstring,而不是使用注释吧。

数据分析咨询请扫描二维码

最新资讯
更多
客服在线
立即咨询