简体   繁体   English

Python 3内置函数和类

[英]Python 3 built-in functions and classes

When I am creating a list using below statement 当我使用以下语句创建list

a = list('jane')

Am I calling Python's built-in list function or instantiating list class. 我是在调用Python的内置list函数还是实例化list类。

My understanding is we are instantiating list class by passing 'jane' as argument. 我的理解是我们通过传递'jane'作为参数来实例化list类。

However, the Python's documentation https://docs.python.org/3/library/functions.html says list() is built-in function. 但是,Python的文档https://docs.python.org/3/library/functions.html表示list()是内置函数。

Your question is answered by the very documentation page you mention : 提到的文档页面将回答您的问题:

class list([iterable])
Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range . List实际上不是可变的序列类型,而是ListSequence Types(list,tuple,range)中记录的,而不是一个可变的序列类型。

In Python, both classes and functions are callable, so in practice, you can treat them alike. 在Python中,类和函数都是可调用的,因此在实践中,您可以将它们视为相同。

The docs explicitly say: 文档明确指出:

class list([iterable])

Rather than being a function, list is actually a mutable sequence type list实际上不是可变函数,而是可变的序列类型

You can easily check that: 您可以轻松检查以下内容:

>>> type(list)
type

if it was a function, function would be the output provided by using type . 如果它是一个函数,那么function将是使用type提供的输出。

You're instantiating a list object the same way you'd do if you created your own class and called it. 实例化list对象的方式与创建自己的类并调用它的方式相同。 type 's __call__ is essentially getting invoked and sets up your instance so, though they aren't a function per se, they are callable. type__call__本质上会被调用并设置您的实例,因此,尽管它们本身不是函数,但它们是可调用的。


The fact that they are listed in that specific section is probably for convenience, it might be confusing but reading the description of it is supposed to disambiguate this. 它们在该特定部分中列出的事实可能是为了方便起见,这可能会使您感到困惑,但是阅读该说明会消除歧义。

You are instantiating a list. 您正在实例化一个列表。

class list([iterable]) Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range. class list([iterable]) list实际上不是可变的,而是可变的序列类型,如Lists和Sequence Types(列表,元组,范围)中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM