【问题标题】:python function with a pass in it [duplicate]带有传递的python函数[重复]
【发布时间】:2017-06-30 02:36:51
【问题描述】:

在许多代码中,我看到带有函数的类,它们只是使用了pass 短语并对它们进行了一些评论。 喜欢这个来自 python 的原生内置函数:

def copyright(*args, **kwargs): # real signature unknown
"""
interactive prompt objects for printing the license text, a list of
    contributors and the copyright notice.
"""
pass

我知道 pass 什么都不做,它是一种冷漠和null 的短语,但是程序员为什么要使用这样的函数呢?

还有一些带有return ""的功能,比如:

def bin(number): # real signature unknown; restored from __doc__
"""
bin(number) -> string

Return the binary representation of an integer.

   >>> bin(2796202)
   '0b1010101010101010101010'
"""
return ""

为什么程序员使用这些东西?

【问题讨论】:

    标签: python python-3.x null python-2.x


    【解决方案1】:

    您的 IDE 在欺骗您。这些功能实际上并不像那样。您的 IDE 编造了一堆与真实的源代码几乎没有相似之处的假源代码。这就是为什么它说像# real signature unknown 这样的东西。我不知道他们为什么认为这是个好主意。

    真正的代码看起来完全不同。比如这里是真正的bin(Python 2.7版本):

    static PyObject *
    builtin_bin(PyObject *self, PyObject *v)
    {
        return PyNumber_ToBase(v, 2);
    }
    
    PyDoc_STRVAR(bin_doc,
    "bin(number) -> string\n\
    \n\
    Return the binary representation of an integer or long integer.");
    

    它是用 C 语言编写的,它是作为 C 函数 PyNumber_ToBase 的简单包装器实现的:

    PyObject *
    PyNumber_ToBase(PyObject *n, int base)
    {
        PyObject *res = NULL;
        PyObject *index = PyNumber_Index(n);
    
        if (!index)
            return NULL;
        if (PyLong_Check(index))
            res = _PyLong_Format(index, base, 0, 1);
        else if (PyInt_Check(index))
            res = _PyInt_Format((PyIntObject*)index, base, 1);
        else
            /* It should not be possible to get here, as
               PyNumber_Index already has a check for the same
               condition */
            PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
                            "int or long");
        Py_DECREF(index);
        return res;
    }
    

    【讨论】:

    • 我想 JetBrains(因为它是他们)这样做是为了让您可以浏览库模块并最终找到记录在案的死胡同,而不仅仅是不允许您按照名称来定义它。
    • 这很奇怪,似乎值得报告错误
    【解决方案2】:

    这是一个待定(待完成)的事情 你知道你需要这个函数,你知道给它什么,你知道它返回什么,但是你现在不打算写它,所以你做一个“原型”

    有时软件包会附带这些函数,因为它们希望您继承并覆盖它们

    【讨论】:

    • 一个似是而非的猜测,但真正的原因完全不同。请注意,这些是内置对象,例如存在的内置 bin 函数或 copyright 对象,因此您可以在交互模式下键入 copyright 并获得版权消息。它们已经实施了。
    猜你喜欢
    • 2016-06-29
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    相关资源
    最近更新 更多