list()是否被视为函数? [英] Is `list()` considered a function?
问题描述
list
显然是内置类型 Python.我在此问题下看到一条评论,该问题将list()
称为内置函数.而且,当我们检查文档时,它确实包含在内置函数列表中,但文档再次指出:
list
is obviously a built-in type in Python. I saw a comment under this question which calls list()
a built-in function. And when we check the documentation, it is, indeed, included in Built-in functions list but the documentation again states:
列表实际上不是可变函数,而是可变的序列类型
Rather than being a function, list is actually a mutable sequence type
这带给我的问题是:list()
被视为函数吗?我们可以将其称为内置函数吗?
Which brings me to my question: Is list()
considered a function? Can we refer to it as a built-in function?
如果我们在谈论C ++,我会说我们只是在调用构造函数,但是我不确定constructor
一词是否适用于Python(在这种情况下从未遇到过).
If we were talking about C++, I'd say we are just calling the constructor, but I am not sure if the term constructor
applies to Python (never encountered its use in this context).
推荐答案
list
是type
,这意味着它在某处被定义为类,就像int
和float
一样.
list
is a type
, which means it is defined somewhere as a class, just like int
and float
.
>> type(list)
<class 'type'>
如果您在builtins.py
中检查其定义(实际代码在C中实现)
If you check its definition in builtins.py
(the actual code is implemented in 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()
不是函数.就像任何对CustomClass()
的调用一样,它只是在调用list.__init__()
(带有一些与本讨论无关的参数).
So, list()
is not a function. It is just calling list.__init__()
(with some arguments which are irrelevant for this discussion) just like any call to CustomClass()
is doing.
感谢@jpg添加注释:Python中的类和函数具有一个公共属性:它们都被视为 callables ,这意味着它们可以用()
调用.有一个内置函数callable
,它检查给定的参数是否可调用:
Thanks for @jpg for adding in the comments: classes and functions in Python have a common property: they are both considered as callables, which means they are allowed to be invoked with ()
. There is a built-in function callable
that checks if the given argument is callable:
>> callable(1)
False
>> callable(int)
True
>> callable(list)
True
>> callable(callable)
True
在builtins.py
中也定义了
callable
:
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
这篇关于list()是否被视为函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!