什么是python的_random?

时间:2017-01-04 22:01:15

标签: python python-2.7

如果您打开random.py以查看其工作原理,则其类Random子类_random.Random

import _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.  Especially useful for multi-threaded programs, creating
    a different instance of Random for each thread, and using the jumpahead()
    method to ensure that the generated sequences seen by each thread don't
    overlap.

    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(), setstate() and jumpahead().
    Optionally, implement a getrandbits() method so that randrange() can cover
    arbitrarily large ranges.

    """

我可以通过以下方式轻松找到文件random.py

In [1]: import sys
In [2]: print random.__file__
/usr/lib/python2.7/random.pyc

_random没有此变量:

In [3]: _random.__file__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-295-a62b7df330e2> in <module>()
----> 1 _random.__file__

AttributeError: 'module' object has no attribute '__file__'

那么什么是_random,为什么random将其子类化,我在哪里可以找到相应的文件?

2 个答案:

答案 0 :(得分:8)

对于在C中实现的模块,通常使用前导下划线。通常使用此C模块的模​​式_mod和导入此mod的Python模块的_mod 。您可以在标准库的多个模块中找到它。通常,您应该使用mod而不是_mod

在Mac OS X上有一个文件:

_random.so

在Python使用的共享库的目录中。

只需在交互式提示符下键入模块名称即可查看路径:

>>> _random
>>> <module '_random' from '/path/to/python/sharedlibs/_random.so'>

顺便说一句,并非所有可导入的模块都有与之关联的文件。有些是Python可执行文件的一部分,内置模块:

>>> import sys
>>> sys.builtin_module_names
('_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale',
 '_operator', '_signal', '_sre', '_stat', '_string', '_symtable', '_thread',
 '_tracemalloc', '_warnings', '_weakref', 'atexit', 'builtins', 'errno', 
 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 
 'time', 'xxsubtype', 'zipimport')

所以,如果你进入你的平台:

>>> _random
_random <module '_random' (built-in)>

_random是Python可执行文件的一部分。

在C源代码_randommodule.c中,您可以找到可在Python中使用的Random方法:

static PyMethodDef random_methods[] = {
    {"random",          (PyCFunction)random_random,  METH_NOARGS,
        PyDoc_STR("random() -> x in the interval [0, 1).")},
    {"seed",            (PyCFunction)random_seed,  METH_VARARGS,
        PyDoc_STR("seed([n]) -> None.  Defaults to current time.")},
    {"getstate",        (PyCFunction)random_getstate,  METH_NOARGS,
        PyDoc_STR("getstate() -> tuple containing the current state.")},
    {"setstate",          (PyCFunction)random_setstate,  METH_O,
        PyDoc_STR("setstate(state) -> None.  Restores generator state.")},
    {"getrandbits",     (PyCFunction)random_getrandbits,  METH_VARARGS,
        PyDoc_STR("getrandbits(k) -> x.  Generates an int with "
                  "k random bits.")},
    {NULL,              NULL}           /* sentinel */
};

比较:

>>> [x for x in dir(_random.Random) if not x.startswith('__')]
['getrandbits', 'getstate', 'jumpahead', 'random', 'seed', 'setstate']

答案 1 :(得分:4)

它是对C Python的_random module的引用。它是用C实现的,所以没有.py文件可供查找。