【问题标题】:Is `list()` considered a function?`list()` 被认为是一个函数吗?
【发布时间】:2019-05-08 01:33:14
【问题描述】:

list 在 Python 中显然是 a built-in type。我在this 问题下看到了一条评论,它调用list() 一个内置函数。当我们检查文档时,它确实包含在 Built-in functions list 中,但文档再次指出:

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

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

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

【问题讨论】:

  • 我会说“构造函数”已经足够接近了。毕竟,如果你有任何其他自定义类,比如说Foo,那么Foo 也是一个type,也是一个可调用函数(构造函数)。

标签: python list function


【解决方案1】:

list 是一个type,这意味着它在某处被定义为一个类,就像intfloat

>> 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

所以,list() 不是一个函数。它只是调用list.__init__()(带有一些与本次讨论无关的参数),就像对CustomClass() 的任何调用一样。

感谢@jpg 添加 cmets:Python 中的类和函数有一个共同的属性:它们都被视为 callables,这意味着它们可以被 () 调用。有一个内置函数 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

【讨论】:

  • 从概念上讲,在 Python 中,值得注意的是带有 __init__ 的类和函数都是 可调用 对象。它们只是共享一个共同特征。内置的callable 让您可以测试它。
  • 现在我的理解是:不,尽管它在内置函数列表中,但它不是一个函数,而是一个 type 对象,恰好是 callable , 是的,__init__ 实际上在 Python 中被称为 constructor。对吗?
  • @Ayxan 本身。我个人不喜欢将__init__ 称为构造函数(因为那您将如何引用__new__?)。正如docs 所暗示的那样,__init__ 仅在创建对象后调用,并且初始化它的属性,它不会创建它。
  • callable() 的签名是 callable(obj) - 它需要任何类型的对象。
【解决方案2】:

当您调用 list() 时,您正在调用 list 类 (list.__init__) 的构造函数。

如果您对 Python 中“构造函数”一词的使用有任何疑问,list 的实现者选择引用 __init__ 的确切词是:

https://github.com/python/cpython/blob/master/Objects/listobject.c#L2695

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2012-04-08
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多