2. 內建函式

Python 直譯器有內建數十個函式,隨時都可以使用這些函式。以下按照英文字母排序列出。

內建函式

abs()

dict()

help()

min()

setattr()

all()

dir()

hex()

next()

slice()

any()

divmod()

id()

object()

sorted()

ascii()

enumerate()

input()

oct()

staticmethod()

bin()

eval()

int()

open()

str()

bool()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

delattr()

hash()

memoryview()

set()

abs(x)

Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.

all(iterable)

如果 iterable 的所有元素为真(或迭代器为空),返回 True 。等价于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
any(iterable)

如果 iterable 的任一元素为真则返回 True。 如果迭代器为空,返回 False。 等价于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
ascii(object)

就像函数 repr(),返回一个对象可打印的字符串,但是 repr() 返回的字符串中非 ASCII 编码的字符,会使用 \x\u\U 来转义。生成的字符串和 Python 2 的 repr() 返回的结果相似。

bin(x)

将一个整数转变为一个前缀为“0b”的二进制字符串。结果是一个合法的 Python 表达式。如果 x 不是 Python 的 int 对象,那它需要定义 __index__() 方法返回一个整数。一些例子:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

如果不一定需要前缀“0b”,还可以使用如下的方法。

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

另见 format() 获取更多信息。

class bool([x])

返回一个布尔值,True 或者 Falsex 使用标准的 真值测试过程 来转换。如果 x 是假的或者被省略,返回 False;其他情况返回 Truebool 类是 int 的子类(参见 Numeric Types — int, float, complex)。其他类不能继承自它。它只有 FalseTrue 两个实例(参见 Boolean Values)。

class bytearray([source[, encoding[, errors]]])

返回一个新的 bytes 数组。 bytearray 类是一个可变序列,包含范围为 0 <= x < 256 的整数。它有可变序列大部分常见的方法,见 Mutable Sequence Types 的描述;同时有 bytes 类型的大部分方法,参见 Bytes and Bytearray Operations

可选形参 source 可以用不同的方式来初始化数组:

  • 如果是一个 string,您必须提供 encoding 参数(errors 参数仍是可选的);bytearray() 会使用 str.encode() 方法来将 string 转变成 bytes。

  • 如果是一个 integer,会初始化大小为该数字的数组,并使用 null 字节填充。

  • 如果是一个符合 buffer 接口的对象,该对象的只读 buffer 会用来初始化字节数组。

  • 如果是一个 iterable 可迭代对象,它的元素的范围必须是 0 <= x < 256 的整数,它会被用作数组的初始内容。

如果没有实参,则创建大小为 0 的数组。

另见 Binary Sequence Types — bytes, bytearray, memoryviewBytearray Objects

class bytes([source[, encoding[, errors]]])

返回一个新的“bytes”对象, 是一个不可变序列,包含范围为 0 <= x < 256 的整数。bytesbytearray 的不可变版本 - 它有其中不改变序列的方法和相同的索引、切片操作。

因此,构造函数的实参和 bytearray() 相同。

字节对象还可以用字面值创建,参见 String and Bytes literals

另见 Binary Sequence Types — bytes, bytearray, memoryviewBytes ObjectsBytes and Bytearray Operations

callable(object)

如果实参 object 是可调用的,返回 True,否则返回 False。如果返回真,调用仍可能会失败;但如果返回假,则调用 object 肯定会失败。注意类是可调用的(调用类会返回一个新的实例)。如果实例的类有 __call__() 方法,则它是可调用。

3.2 版新加入: 这个函数一开始在 Python 3.0 被移除了,但在 Python 3.2 被重新加入。

chr(i)

返回 Unicode 码位为整数 i 的字符的字符串格式。例如,chr(97) 返回字符串 'a'chr(8364) 返回字符串 '€'。这是 ord() 的逆函数。

实参的合法范围是 0 到 1,114,111(16 进制表示是 0x10FFFF)。如果 i 超过这个范围,会触发 ValueError 异常。

@classmethod

把一个方法封装成类方法。

一个类方法把类自己作为第一个实参,就像一个实例方法把实例自己作为第一个实参。请用以下习惯来声明类方法:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

source 编译成代码或 AST 对象。代码对象可以被 exec()eval() 执行。source 可以是常规的字符串、字节字符串,或者 AST 对象。参见 ast 模块的文档了解如何使用 AST 对象。

filename 实参需要是代码读取的文件名;如果代码不需要从文件中读取,可以传入一些可辨识的值(经常会使用 '<string>')。

mode 实参指定了编译代码必须用的模式。如果 source 是语句序列,可以是 'exec';如果是单一表达式,可以是 'eval';如果是单个交互式语句,可以是 'single'。(在最后一种情况下,如果表达式执行结果不是 None 将会被打印出来。)

The optional arguments flags and dont_inherit control which future statements affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile(). If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the future statements in effect around the call to compile are ignored.

Future 语句使用比特位来指定,多个语句可以通过按位或来指定。具体特性的比特位可以通过 __future__ 模块中的 _Feature 类的实例的 compiler_flag 属性来获得。

optimize 实参指定编译器的优化级别;默认值 -1 选择与解释器的 -O 选项相同的优化级别。显式级别为 0 (没有优化;__debug__ 为真)、1 (断言被删除, __debug__ 为假)或 2 (文档字符串也被删除)。

如果编译的源码不合法,此函数会触发 SyntaxError 异常;如果源码包含 null 字节,则会触发 ValueError 异常。

如果您想分析 Python 代码的 AST 表示,请参阅 ast.parse()

備註

'single''eval' 模式编译多行代码字符串时,输入必须以至少一个换行符结尾。 这使 code 模块更容易检测语句的完整性。

警告

在将足够大或者足够复杂的字符串编译成 AST 对象时,Python 解释器有可以因为 Python AST 编译器的栈深度限制而崩溃。

3.2 版更變: 允许使用 Windows 和 Mac 的换行符。在 'exec' 模式不再需要以换行符结尾。增加了 optimize 形参。

3.5 版更變: 之前 source 中包含 null 字节的话会触发 TypeError 异常。

class complex([real[, imag]])

返回值为 real + imag*1j 的复数,或将字符串或数字转换为复数。如果第一个形参是字符串,则它被解释为一个复数,并且函数调用时必须没有第二个形参。第二个形参不能是字符串。每个实参都可以是任意的数值类型(包括复数)。如果省略了 imag,则默认值为零,构造函数会像 intfloat 一样进行数值转换。如果两个实参都省略,则返回 0j

備註

当从字符串转换时,字符串在 +- 的周围必须不能有空格。例如 complex('1+2j') 是合法的,但 complex('1 + 2j') 会触发 ValueError 异常。

Numeric Types — int, float, complex 描述了复数类型。

3.6 版更變: 您可以使用下划线将代码文字中的数字进行分组。

delattr(object, name)

setattr() 相关的函数。实参是一个对象和一个字符串。该字符串必须是对象的某个属性。如果对象允许,该函数将删除指定的属性。例如 delattr(x, 'foobar') 等价于 del x.foobar

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

创建一个新的字典。dict 对象是一个字典类。参见 dictMapping Types — dict 了解这个类。

其他容器类型,请参见内置的 listsettuple 类,以及 collections 模块。

dir([object])

如果没有实参,则返回当前本地作用域中的名称列表。如果有实参,它会尝试返回该对象的有效属性列表。

如果对象有一个名为 __dir__() 的方法,那么该方法将被调用,并且必须返回一个属性列表。这允许实现自定义 __getattr__()__getattribute__() 函数的对象能够自定义 dir() 来报告它们的属性。

如果对象不提供 __dir__(),这个函数会尝试从对象已定义的 __dict__ 属性和类型对象收集信息。结果列表并不总是完整的,如果对象有自定义 __getattr__(),那结果可能不准确。

默认的 dir() 机制对不同类型的对象行为不同,它会试图返回最相关而不是最全的信息:

  • 如果对象是模块对象,则列表包含模块的属性名称。

  • 如果对象是类型或类对象,则列表包含它们的属性名称,并且递归查找所有基类的属性。

  • 否则,列表包含对象的属性名称,它的类属性名称,并且递归查找它的类的所有基类的属性。

返回的列表按字母表排序。例如:

>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module # doctest: +SKIP
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

備註

因为 dir() 主要是为了便于在交互式时使用,所以它会试图返回人们感兴趣的名字集合,而不是试图保证结果的严格性或一致性,它具体的行为也可能在不同版本之间改变。例如,当实参是一个类时,metaclass 的属性不包含在结果列表中。

divmod(a, b)

它将两个(非复数)数字作为实参,并在执行整数除法时返回一对商和余数。对于混合操作数类型,适用双目算术运算符的规则。对于整数,结果和 (a // b, a % b) 一致。对于浮点数,结果是 (q, a % b)q 通常是 math.floor(a / b) 但可能会比 1 小。在任何情况下, q * b + a % ba 基本相等;如果 a % b 非零,它的符号和 b 一样,并且 0 <= abs(a % b) < abs(b)

enumerate(iterable, start=0)

返回一个枚举对象。iterable 必须是一个序列,或 iterator,或其他支持迭代的对象。 enumerate() 返回的迭代器的 __next__() 方法返回一个元组,里面包含一个计数值(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

等价于:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
eval(expression, globals=None, locals=None)

实参是一个字符串,以及可选的 globals 和 locals。globals 实参必须是一个字典。locals 可以是任何映射对象。

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> eval('x+1')
2

这个函数也可以用来执行任何代码对象(如 compile() 创建的)。这种情况下,参数是代码对象,而不是字符串。如果编译该对象时的 mode 实参是 'exec' 那么 eval() 返回值为 None

提示: exec() 函数支持动态执行语句。 globals()locals() 函数各自返回当前的全局和本地字典,因此您可以将它们传递给 eval()exec() 来使用。

另外可以参阅 ast.literal_eval(),该函数可以安全执行仅包含文字的表达式字符串。

exec(object[, globals[, locals]])

这个函数支持动态执行 Python 代码。object 必须是字符串或者代码对象。如果是字符串,那么该字符串将被解析为一系列 Python 语句并执行(除非发生语法错误)。1 如果是代码对象,它将被直接执行。在任何情况下,被执行的代码都需要和文件输入一样是有效的(见参考手册中关于文件输入的章节)。请注意即使在传递给 exec() 函数的代码的上下文中,returnyield 语句也不能在函数定义之外使用。该函数返回值是 None

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

如果 globals 字典不包含 __builtins__ 键值,则将为该键插入对内建 builtins 模块字典的引用。因此,在将执行的代码传递给 exec() 之前,可以通过将自己的 __builtins__ 字典插入到 globals 中来控制可以使用哪些内置代码。

備註

内置 globals()locals() 函数各自返回当前的全局和本地字典,因此可以将它们传递给 exec() 的第二个和第三个实参。

備註

默认情况下,locals 的行为如下面 locals() 函数描述的一样:不要试图改变默认的 locals 字典。如果您想在 exec() 函数返回时知道代码对 locals 的变动,请明确地传递 locals 字典。

filter(function, iterable)

iterable 中函数 function 返回真的那些元素,构建一个新的迭代器。iterable 可以是一个序列,一个支持迭代的容器,或一个迭代器。如果 functionNone ,则会假设它是一个身份函数,即 iterable 中所有返回假的元素会被移除。

请注意, filter(function, iterable) 相当于一个生成器表达式,当 function 不是 None 的时候为 (item for item in iterable if function(item));function 是 None 的时候为 (item for item in iterable if item)

请参阅 itertools.filterfalse() 了解,只有 function 返回 false 时才选取 iterable 中元素的补充函数。

class float([x])

返回从数字或字符串 x 生成的浮点数。

如果实参是字符串,则它必须是包含十进制数字的字符串,字符串前面可以有符号,之前也可以有空格。可选的符号有 '+''-''+' 对创建的值没有影响。实参也可以是 NaN(非数字)、正负无穷大的字符串。确切地说,除去首尾的空格后,输入必须遵循以下语法:

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=  floatnumber | infinity | nan
numeric_string ::=  [sign] numeric_value

这里, floatnumber 是 Python 浮点数的字符串形式,详见 Floating point literals。字母大小写都可以,例如,“inf”、“Inf”、“INFINITY”、“iNfINity” 都可以表示正无穷大。

另一方面,如果实参是整数或浮点数,则返回具有相同值(在 Python 浮点精度范围内)的浮点数。如果实参在 Python 浮点精度范围外,则会触发 OverflowError

For a general Python object x, float(x) delegates to x.__float__().

如果没有实参,则返回 0.0

例如:

>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

Numeric Types — int, float, complex 描述了浮点类型。

3.6 版更變: 您可以使用下划线将代码文字中的数字进行分组。

format(value[, format_spec])

value 转换为 format_spec 控制的“格式化”表示。format_spec 的解释取决于 value 实参的类型,但是大多数内置类型使用标准格式化语法:Format Specification Mini-Language

默认的 format_spec 是一个空字符串,它通常和调用 str(value) 的结果相同。

调用 format(value, format_spec) 会转换成 type(value).__format__(value, format_spec) ,所以实例字典中的 __format__() 方法将不会调用。如果搜索到 object 有这个方法但 format_spec 不为空,format_spec 或返回值不是字符串,会触发 TypeError 异常。

3.4 版更變: format_spec 不是空字符串时, object().__format__(format_spec) 会触发 TypeError

class frozenset([iterable])

返回一个新的 frozenset 对象,它包含可选参数 iterable 中的元素。 frozenset 是一个内置的类。有关此类的文档,请参阅 frozensetSet Types — set, frozenset

请参阅内建的 setlisttupledict 类,以及 collections 模块来了解其它的容器。

getattr(object, name[, default])

返回对象命名属性的值。name 必须是字符串。如果该字符串是对象的属性之一,则返回该属性的值。例如, getattr(x, 'foobar') 等同于 x.foobar。如果指定的属性不存在,且提供了 default 值,则返回它,否则触发 AttributeError

globals()

返回表示当前全局符号表的字典。这总是当前模块的字典(在函数或方法中,不是调用它的模块,而是定义它的模块)。

hasattr(object, name)

该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称,则返回 True,否则返回 False。(此功能是通过调用 getattr(object, name) 看是否有 AttributeError 异常来实现的。)

hash(object)

返回该对象的哈希值(如果它有的话)。哈希值是整数。它们在字典查找元素时用来快速比较字典的键。相同大小的数字变量有相同的哈希值(即使它们类型不同,如 1 和 1.0)。

備註

如果对象实现了自己的 __hash__() 方法,请注意,hash() 根据机器的字长来截断返回值。另请参阅 __hash__()

help([object])

启动内置的帮助系统(此函数主要在交互式中使用)。如果没有实参,解释器控制台里会启动交互式帮助系统。如果实参是一个字符串,则在模块、函数、类、方法、关键字或文档主题中搜索该字符串,并在控制台上打印帮助信息。如果实参是其他任意对象,则会生成该对象的帮助页。

该函数通过 site 模块加入到内置命名空间。

3.4 版更變: pydocinspect 的变更使得可调用对象的签名信息更加全面和一致。

hex(x)

将整数转换为以“0x”为前缀的小写十六进制字符串。如果 x 不是 Python int 对象,则必须定义返回整数的 __index__() 方法。一些例子:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

如果要将整数转换为大写或小写的十六进制字符串,并可选择有无“0x”前缀,则可以使用如下方法:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

另见 format() 获取更多信息。

另请参阅 int() 将十六进制字符串转换为以 16 为基数的整数。

備註

如果要获取浮点数的十六进制字符串形式,请使用 float.hex() 方法。

id(object)

返回对象的“标识值”。该值是一个整数,在此对象的生命周期中保证是唯一且恒定的。两个生命期不重叠的对象可能具有相同的 id() 值。

CPython implementation detail: This is the address of the object in memory.

input([prompt])

如果存在 prompt 实参,则将其写入标准输出,末尾不带换行符。接下来,该函数从输入中读取一行,将其转换为字符串(除了末尾的换行符)并返回。当读取到 EOF 时,则触发 EOFError。例如:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

如果加载了 readline 模块,input() 将使用它来提供复杂的行编辑和历史记录功能。

class int(x=0)
class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.

如果 x 不是数字,或者有 base 参数,x 必须是字符串、bytes、表示进制为 base整数字面值bytearray 实例。该文字前可以有 +- (中间不能有空格),前后可以有空格。一个进制为 n 的数字包含 0 到 n-1 的数,其中 az (或 AZ )表示 10 到 35。默认的 base 为 10 ,允许的进制有 0、2-36。2、8、16 进制的数字可以在代码中用 0b/0B0o/0O0x/0X 前缀来表示。进制为 0 将安照代码的字面量来精确解释,最后的结果会是 2、8、10、16 进制中的一个。所以 int('010', 0) 是非法的,但 int('010')int('010', 8) 是合法的。

整数类型定义请参阅 Numeric Types — int, float, complex

3.4 版更變: 如果 base 不是 int 的实例,但 base 对象有 base.__index__ 方法,则会调用该方法来获取进制数。以前的版本使用 base.__int__ 而不是 base.__index__

3.6 版更變: 您可以使用下划线将代码文字中的数字进行分组。

isinstance(object, classinfo)

如果 object 实参是 classinfo 实参的实例,或者是(直接、间接或 虚拟)子类的实例,则返回 true。如果 object 不是给定类型的对象,函数始终返回 false。如果 classinfo 是对象类型(或多个递归元组)的元组,如果 object 是其中的任何一个的实例则返回 true。 如果 classinfo 既不是类型,也不是类型元组或类型的递归元组,那么会触发 TypeError 异常。

issubclass(class, classinfo)

如果 classclassinfo 的子类(直接、间接或 虚拟 的),则返回 true。classinfo 可以是类对象的元组,此时 classinfo 中的每个元素都会被检查。其他情况,会触发 TypeError 异常。

iter(object[, sentinel])

返回一个 iterator 对象。根据是否存在第二个实参,第一个实参的解释是非常不同的。如果没有第二个实参,object 必须是支持迭代协议(有 __iter__() 方法)的集合对象,或必须支持序列协议(有 __getitem__() 方法,且数字参数从 0 开始)。如果它不支持这些协议,会触发 TypeError。如果有第二个实参 sentinel,那么 object 必须是可调用的对象。这种情况下生成的迭代器,每次迭代调用它的 __next__() 方法时都会不带实参地调用 object;如果返回的结果是 sentinel 则触发 StopIteration,否则返回调用结果。

另请参阅 Iterator Types

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)
len(s)

返回对象的长度(元素个数)。实参可以是序列(如 string、bytes、tuple、list 或 range 等)或集合(如 dictionary、set 或 frozen set 等)。

class list([iterable])

虽然被称为函数,list 实际上是一种可变序列类型,详情请参阅 List(串列)Sequence Types — list, tuple, range

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

備註

不要更改此字典的内容;更改不会影响解释器使用的局部变量或自由变量的值。

map(function, iterable, ...)

返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器。 如果传入了额外的 iterable 参数,function 必须接受相同个数的实参并被应用于从所有可迭代对象中并行获取的项。 当有多个可迭代对象时,最短的可迭代对象耗尽则整个迭代就将结束。 对于函数的输入已经是参数元组的情况,请参阅 itertools.starmap()

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

返回可迭代对象中最大的元素,或者返回两个及以上实参中最大的。

如果只提供了一个位置参数,它必须是非空 iterable,返回可迭代对象中最大的元素;如果提供了两个及以上的位置参数,则返回最大的位置参数。

有两个可选只能用关键字的实参。key 实参指定排序函数用的参数,如传给 list.sort() 的。default 实参是当可迭代对象为空时返回的值。如果可迭代对象为空,并且没有给 default ,则会触发 ValueError

如果有多个最大元素,则此函数将返回第一个找到的。这和其他稳定排序工具如 sorted(iterable, key=keyfunc, reverse=True)[0]heapq.nlargest(1, iterable, key=keyfunc) 保持一致。

3.4 版新加入: keyword-only 实参 default

memoryview(obj)

返回由给定实参创建的“内存视图”对象。有关详细信息,请参阅 Memory Views

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

返回可迭代对象中最小的元素,或者返回两个及以上实参中最小的。

如果只提供了一个位置参数,它必须是 iterable,返回可迭代对象中最小的元素;如果提供了两个及以上的位置参数,则返回最小的位置参数。

有两个可选只能用关键字的实参。key 实参指定排序函数用的参数,如传给 list.sort() 的。default 实参是当可迭代对象为空时返回的值。如果可迭代对象为空,并且没有给 default ,则会触发 ValueError

如果有多个最小元素,则此函数将返回第一个找到的。这和其他稳定排序工具如 sorted(iterable, key=keyfunc)[0]heapq.nsmallest(1, iterable, key=keyfunc) 保持一致。

3.4 版新加入: keyword-only 实参 default

next(iterator[, default])

通过调用 iterator__next__() 方法获取下一个元素。如果迭代器耗尽,则返回给定的 default,如果没有默认值则触发 StopIteration

class object

返回一个没有特征的新对象。object 是所有类的基类。它具有所有 Python 类实例的通用方法。这个函数不接受任何实参。

備註

由于 object 没有 __dict__,因此无法将任意属性赋给 object 的实例。

oct(x)

将一个整数转变为一个前缀为“0o”的八进制字符串。结果是一个合法的 Python 表达式。如果 x 不是 Python 的 int 对象,那它需要定义 __index__() 方法返回一个整数。一些例子:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

如果要将整数转换为八进制字符串,并可选择有无“0o”前缀,则可以使用如下方法:

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

另见 format() 获取更多信息。

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

打开 file 并返回对应的 file object。如果该文件不能打开,则触发 OSError

file 是一个 path-like object,表示将要打开的文件的路径(绝对路径或者当前工作目录的相对路径),也可以是要被封装的整数类型文件描述符。(如果是文件描述符,它会随着返回的 I/O 对象关闭而关闭,除非 closefd 被设为 False 。)

mode 是一个可选字符串,用于指定打开文件的模式。默认值是 'r' ,这意味着它以文本模式打开并读取。其他常见模式有:写入 'w' (截断已经存在的文件);排它性创建 'x' ;追加写 'a' (在 一些 Unix 系统上,无论当前的文件指针在什么位置,所有 写入都会追加到文件末尾)。在文本模式,如果 encoding 没有指定,则根据平台来决定使用的编码:使用 locale.getpreferredencoding(False) 来获取本地编码。(要读取和写入原始字节,请使用二进制模式并不要指定 encoding。)可用的模式有:

字符

意义

'r'

读取(默认)

'w'

写入,并先截断文件

'x'

排它性创建,如果文件已存在则失败

'a'

写入,如果文件存在则在末尾追加

'b'

二进制模式

't'

文本模式(默认)

'+'

更新磁盘文件(读取并写入)

'U'

universal newlines mode (deprecated)

默认的模式是 'r' (打开并读取文本,同 'rt' )。对于二进制写入, 'w+b' 模式打开并把文件截断成 0 字节; 'r+b' 则不会截断。

As mentioned in the 總覽, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

備註

Python doesn’t depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s 「block size」 and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

  • 「Interactive」 text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.

  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.

  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.

  • 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.

  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.

  • 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences.

  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).

新创建的文件是 不可继承的

下面的示例使用 os.open() 函数的 dir_fd 的形参,从给定的目录中用相对路径打开文件:

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.

另请参阅文件操作模块,例如 fileinputio (声明了 open())、osos.pathtempfileshutil

3.3 版更變:
  • 增加了 opener 形参。

  • 增加了 'x' 模式。

  • 过去触发的 IOError,现在是 OSError 的别名。

  • 如果文件已存在但使用了排它性创建模式( 'x' ),现在会触发 FileExistsError

3.4 版更變:
  • 文件现在禁止继承。

Deprecated since version 3.4, will be removed in version 4.0: 'U' 模式。

3.5 版更變:
  • 如果系统调用被中断,但信号处理程序没有触发异常,此函数现在会重试系统调用,而不是触发 InterruptedError 异常(原因详见 PEP 475)。

  • 增加了 'namereplace' 错误处理接口。

3.6 版更變:
ord(c)

对表示单个 Unicode 字符的字符串,返回代表它 Unicode 码点的整数。例如 ord('a') 返回整数 97ord('€') (欧元符号)返回 8364 。这是 chr() 的逆函数。

pow(x, y[, z])

返回 xy 次幂;如果 z 存在,则对 z 取余(比直接 pow(x, y) % z 计算更高效)。两个参数形式的 pow(x, y) 等价于幂运算符: x**y

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

3.3 版更變: 增加了 flush 关键字参数。

class property(fget=None, fset=None, fdel=None, doc=None)

返回 property 属性。

fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.

A typical use is to define a managed attribute x:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget’s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

The @property decorator turns the voltage() method into a 「getter」 for a read-only attribute with the same name, and it sets the docstring for voltage to 「Get the current voltage.」

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (x in this case.)

The returned property object also has the attributes fget, fset, and fdel corresponding to the constructor arguments.

3.5 版更變: The docstrings of property objects are now writeable.

range(stop)
range(start, stop[, step])

Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

repr(object)

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

reversed(seq)

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number.

For a general Python object number, round delegates to number.__round__.

備註

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See 浮點數運算:問題與限制 for more information.

class set([iterable])

Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

class slice(stop)
class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

sorted(iterable, *, key=None, reverse=False)

Return a new sorted list from the items in iterable.

有兩個選擇性參數,只能使用關鍵字參數指定。

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

For sorting examples and a brief sorting tutorial, see 如何排序.

@staticmethod

Transform a method into a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors.

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:

class C:
    builtin_open = staticmethod(open)

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

Return a str version of object. See str() for details.

str is the built-in string class. For general information about strings, see Text Sequence Type — str.

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

super([type[, object-or-type]])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).

There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement 「diamond diagrams」 where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

For both use cases, a typical superclass call looks like this:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

Note that super() is implemented as part of the binding process for explicit dotted attribute lookups such as super().__getitem__(name). It does so by implementing its own __getattribute__() method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, super() is undefined for implicit lookups using statements or operators such as super()[name].

Also note that, aside from the zero argument form, super() is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.

For practical suggestions on how to design cooperative classes using super(), see guide to using super().

tuple([iterable])

Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.

class type(object)
class type(name, bases, dict)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute. For example, the following two statements create identical type objects:

>>> class X:
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))

See also Type Objects.

3.6 版更變: Subclasses of type which don’t override type.__new__ may no longer use the one-argument form to get the type of an object.

vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip() in conjunction with the * operator can be used to unzip a list:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
__import__(name, globals=None, locals=None, fromlist=(), level=0)

備註

This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], 0)

The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], 0)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

3.3 版更變: Negative values for level are no longer supported (which also changes the default value to 0).

註解

1

解析器只接受 Unix 风格的行结束符。如果您从文件中读取代码,请确保用换行符转换模式转换 Windows 或 Mac 风格的换行符。