`list()` 被认为是一个函数吗?

2024-05-29

list显然是内置类型 https://docs.python.org/3/library/stdtypes.html#list在Python中。我看到底下有一条评论this https://stackoverflow.com/a/53645813/10147399调用的问题list() a 内置功能。当我们检查文档时,它确实包含在内置函数列表 https://docs.python.org/3/library/functions.html但文档再次指出:

列表实际上不是一个函数,而是一个可变序列类型

这让我想到了我的问题:是list()被认为是一个函数?我们可以将其称为内置功能?

如果我们谈论 C++,我会说我们只是调用构造函数,但我不确定这个术语是否constructor适用于Python(从未遇到过它在这种情况下的使用)。


list is a type,这意味着它被定义为一个类,就像int and float.

>> type(list)
<class 'type'>

如果你检查它的定义builtins.py(实际代码是用C实现的):

class list(object):
    """
    Built-in mutable sequence.

    If no argument is given, the constructor creates a new empty list.
    The argument must be an iterable if specified.
    """

    ...

    def __init__(self, seq=()): # known special case of list.__init__
        """
        Built-in mutable sequence.

        If no argument is given, the constructor creates a new empty list.
        The argument must be an iterable if specified.
        # (copied from class doc)
        """
        pass

So, list()不是一个函数。它只是在呼唤list.__init__()(有些参数与本讨论无关)就像任何调用一样CustomClass()是在做。

感谢@jpg添加评论:Python中的类和函数有一个共同的属性:它们都被视为可调用对象,这意味着它们可以被调用()。有一个内置函数callable检查给定的参数是否可调用:

>> callable(1)
False
>> callable(int)
True
>> callable(list)
True
>> callable(callable)
True

callable也定义在builtins.py:

def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
    """
    Return whether the object is callable (i.e., some kind of function).

    Note that classes are callable, as are instances of classes with a
    __call__() method.
    """
    pass
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

`list()` 被认为是一个函数吗? 的相关文章

随机推荐