Skip to main content
 首页 » 编程设计

python之为什么 time.sleep 在通过 True 时不提示

2025年05月04日17kevingrace

所以我刚刚在我的 Python 程序中找到了一个奇怪的错误,这是由于我混淆了函数的参数并错误地将 True 传递给 time.sleep()。 Python 似乎默默地将 True 转换为 1

docs说:

Suspend execution for the given number of seconds. The argument may be a floating point number ...

一般来说,当输入与预期的类型或范围不匹配时,Python 很乐意抛出异常。为什么 sleep 会默默地将 True 转换为数字?

请您参考如下方法:

在python中,Bool是int的子类

>>> issubclass(bool, int) 
True 

这是来自 svn 的源代码:http://svn.python.org/projects/python/trunk/Modules/timemodule.c

PyArg_ParseTuple 使用 d: 说明符将 arg 转换为 float

static PyObject * 
time_sleep(PyObject *self, PyObject *args) 
{ 
    double secs; 
    if (!PyArg_ParseTuple(args, "d:sleep", &secs)) 
        return NULL; 
    if (floatsleep(secs) != 0) 
        return NULL; 
    Py_INCREF(Py_None); 
    return Py_None; 
}