Built-in Functions内置函数

The Python interpreter has a number of functions and types built into it that are always available. Python解释器内置了许多函数和类型,这些函数和类型总是可用的。They are listed here in alphabetical order.它们按字母顺序排列在这里。

Built-in Functions

abs(x)

Return the absolute value of a number. 返回一个数字的绝对值。The argument may be an integer, a floating point number, or an object implementing __abs__(). 参数可以是整数、浮点数或实现__abs__()的对象。If the argument is a complex number, its magnitude is returned.如果参数是复数,则返回其大小。

aiter(async_iterable)

Return an asynchronous iterator for an asynchronous iterable. 返回异步可迭代对象异步迭代器Equivalent to calling x.__aiter__().相当于调用x.__aiter__()

Note: Unlike iter(), aiter() has no 2-argument variant.注意:与iter()不同,aiter()没有2参数变量。

New in version 3.10.3.10版新增。

all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). 如果iterable的所有元素都为True(或者iterable为空),则返回TrueEquivalent to:相当于:

def all(iterable):
for element in iterable:
if not element:
return False
return True
awaitableanext(async_iterator[, default])

When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.等待时,从给定的异步迭代器返回下一项,如果给定且迭代器已耗尽,则返回默认项

This is the async variant of the next() builtin, and behaves similarly.这是next()内置函数的异步变体,其行为类似。

This calls the __anext__() method of async_iterator, returning an awaitable. 这将调用async_iterator__anext__()方法,返回一个awaitableAwaiting this returns the next value of the iterator. 等待返回迭代器的下一个值。If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised.如果给定默认值,则在迭代器耗尽时返回,否则将引发StopAsyncIteration

New in version 3.10.3.10版新增。

any(iterable)

Return True if any element of the iterable is true. 如果iterable的任何元素为True,则返回TrueIf the iterable is empty, return False. 如果iterable为空,则返回FalseEquivalent to:相当于:

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

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u, or \U escapes. 作为repr(),返回包含对象的可打印表示形式的字符串,但使用\x\u\u转义符转义repr()返回的字符串中的非ASCII字符。This generates a string similar to that returned by repr() in Python 2.这将生成一个类似于Python 2中repr()返回的字符串。

bin(x)

Convert an integer number to a binary string prefixed with “0b”. 将整数转换为前缀为“0b”的二进制字符串。The result is a valid Python expression. 结果是一个有效的Python表达式。If x is not a Python int object, it has to define an __index__() method that returns an integer. 如果x不是Python int对象,那么它必须定义一个返回整数的__index__()方法。Some examples:一些示例:

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

If the prefix “0b” is desired or not, you can use either of the following ways.如果需要或不需要前缀“0b”,可以使用以下任一方法。

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

See also format() for more information.有关更多信息,请参阅format()

classbool([x])

Return a Boolean value, i.e. one of True or False. 返回一个布尔值,即TrueFalsex is converted using the standard truth testing procedure. 使用标准真值测试程序转换xIf x is false or omitted, this returns False; otherwise, it returns True. 如果xFalse或省略,则返回False;否则,它将返回TrueThe bool class is a subclass of int (see Numeric Types — int, float, complex). bool类是int的一个子类(参见数值类型-int、float、complex)。It cannot be subclassed further. 它不能再细分了。Its only instances are False and True (see Boolean Values).它唯一的实例是FalseTrue(请参见布尔值)。

Changed in version 3.7: 在3.7版中更改:x is now a positional-only parameter.现在是一个仅用于位置的参数。

breakpoint(*args, **kws)

This function drops you into the debugger at the call site. 此函数将您放入调用站点的调试器中。Specifically, it calls sys.breakpointhook(), passing args and kws straight through. 具体来说,它调用sys.breakpointhook(),直接传递argskwsBy default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. 默认情况下,sys.breakpointhook()调用pdb.set_trace(),不需要任何参数。In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. 在本例中,它纯粹是一个方便的函数,因此您不必显式导入pdb或键入尽可能多的代码来进入调试器。However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.但是,可以将sys.breakpointhook()设置为其他函数,breakpoint()将自动调用该函数,从而允许您进入所选的调试器。

Raises an auditing event builtins.breakpoint with argument breakpointhook.使用参数breakpointhook引发审核事件builtins.breakpoint

New in version 3.7.3.7版新增。

classbytearray([source[, encoding[, errors]]])

Return a new array of bytes. 返回一个新的字节数组。The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. bytearray类是0<=x<256范围内的可变整数序列。It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.它有可变序列类型中描述的大多数可变序列的常用方法,以及bytes类型具有的大多数方法,请参阅字节和字节数组操作

The optional source parameter can be used to initialize the array in a few different ways:可选source参数可用于以几种不同的方式初始化阵列:

  • If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().如果它是一个string,您还必须给出编码(以及可选的error)参数;然后,bytearray()使用str.encode()将字符串转换为字节。

  • If it is an integer, the array will have that size and will be initialized with null bytes.如果是integer,则数组将具有该大小,并将使用空字节初始化。

  • If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.如果它是符合缓冲区接口的对象,则该对象的只读缓冲区将用于初始化字节数组。

  • If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.如果它是一个iterable,那么它必须是0 <=x < 256范围内的整数的iterable,这些整数用作数组的初始内容。

Without an argument, an array of size 0 is created.如果没有参数,将创建大小为0的数组。

See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.另请参见二进制序列类型——字节、字节数组、内存视图字节数组对象

classbytes([source[, encoding[, errors]]])

Return a new “bytes” object which is an immutable sequence of integers in the range 0 <= x < 256. 返回一个新的“字节”对象,它是0 <= x < 256范围内的不可变整数序列。bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.bytesbytearray的一个不可变版本——它具有相同的非变异方法和相同的索引和切片行为。

Accordingly, constructor arguments are interpreted as for bytearray().因此,构造函数参数被解释为bytearray()

Bytes objects can also be created with literals, see String and Bytes literals.字节对象也可以用文字创建,请参阅字符串和字节文字

See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.另请参见二进制序列类型-字节、字节数组、内存视图字节对象以及字节和字节数组操作

callable(object)

Return True if the object argument appears callable, False if not. 如果object参数显示为可调用,则返回True,否则返回FalseIf this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. 如果返回True,调用仍然可能失败,但如果返回False,调用对象将永远不会成功。Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.注意,类是可调用的(调用一个类会返回一个新实例);如果实例的类有一个__call__()方法,则实例是可调用的。

New in version 3.2: 在3.2版中新增:This function was first removed in Python 3.0 and then brought back in Python 3.2.这个函数首先在Python3.0中被删除,然后在Python3.2中被恢复。

chr(i)

Return the string representing a character whose Unicode code point is the integer i. 返回表示Unicode代码点为整数i的字符的字符串。For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. 例如,chr(97)返回字符串'a',而chr(8364)返回字符串'€'This is the inverse of ord().这是ord()的倒数。

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). 参数的有效范围从0到1114111(以16为基数的0x10FFFF)。ValueError will be raised if i is outside that range.如果i超出该范围,则会引发ValueError

@classmethod

Transform a method into a class method.将方法转换为类方法。

A class method receives the class as an implicit first argument, just like an instance method receives the instance. 类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。To declare a class method, use this idiom:要声明类方法,请使用以下习惯用法:

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

The @classmethod form is a function decorator – see Function definitions for details.@classmethod形式是一个函数装饰器——有关详细信息,请参阅函数定义

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). 类方法既可以在类(如C.f())上调用,也可以在实例(如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. 类方法不同于C++或Java静态方法。If you want those, see staticmethod() in this section. 如果需要,请参阅本节中的staticmethod()For more information on class methods, see The standard type hierarchy.有关类方法的更多信息,请参阅标准类型层次结构

Changed in version 3.9: 在3.9版中更改:Class methods can now wrap other descriptors such as property().类方法现在可以包装其他描述符,例如property()

Changed in version 3.10: 在3.10版中更改:Class methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__) and have a new __wrapped__ attribute.类方法现在继承方法属性(__module____name____qualname____doc____annotations__),并具有一个新的__wrapped__属性。

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

Compile the source into a code or AST object. source代码编译成代码或AST对象。Code objects can be executed by exec() or eval(). 代码对象可以由exec()eval()执行。source can either be a normal string, a byte string, or an AST object. source可以是普通字符串、字节字符串或AST对象。Refer to the ast module documentation for information on how to work with AST objects.有关如何使用AST对象的信息,请参阅ast模块文档。

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file ('<string>' is commonly used).filename参数应该给出读取代码的文件;如果不是从文件中读取,则传递一些可识别的值(通常使用'<string>'

The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).mode参数指定必须编译的代码类型;如果source由一系列语句组成,则可以是'exec';如果source由一个表达式组成,则可以是'eval';如果source由一个交互语句组成,则可以是'single'(在后一种情况下,将打印计算结果为非None的表达式语句)。

The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. 可选参数flagsdont_inherit控制哪些编译器选项应该被激活,哪些未来的功能应该被允许。If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling compile(). 如果两者都不存在(或两者都为零),则使用影响调用compile()的代码的相同标志编译代码。If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. 如果给出了flags参数,并且dont_inherit不是(或为零),那么除了那些无论如何都会使用的语句外,还会使用flags参数指定的编译器选项和未来语句。If dont_inherit is a non-zero integer then the flags argument is it – the flags (future features and compiler options) in the surrounding code are ignored.如果dont_inherit是一个非零整数,那么flags参数就是它——周围代码中的标志(未来的特性和编译器选项)将被忽略。

Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. 编译器选项和未来语句由位指定,这些位可以按位或一起指定多个选项。The bitfield required to specify a given future feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module. 可以在__future__模块中的_Feature实例上找到指定给定未来功能所需的位字段作为compiler_flag属性。Compiler flags can be found in ast module, with PyCF_ prefix.编译器标志可以在ast模块中找到,带有PyCF_前缀。

The argument optimize specifies the optimization level of the compiler; the default value of -1 selects the optimization level of the interpreter as given by -O options. 参数optimize指定编译器的优化级别;默认值-1选择解释器的优化级别,如-O选项所示。Explicit levels are 0 (no optimization; __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).显式级别为0(无优化;__debug__true)、1(删除断言,__debug__false)或2(也删除文档字符串)。

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.如果编译的源无效,此函数将引发SyntaxError,如果源包含空字节,则会引发ValueError

If you want to parse Python code into its AST representation, see ast.parse().如果要将Python代码解析为其AST表示形式,请参阅ast.parse()

Raises an auditing event compile with arguments source and filename. 使用参数sourcefilename引发审核事件compileThis event may also be raised by implicit compilation.隐式编译也可能引发此事件。

Note

When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. 'single''eval'模式下使用多行代码编译字符串时,输入必须以至少一个换行符终止。This is to facilitate detection of incomplete and complete statements in the code module.这有助于检测code模块中的不完整和完整语句。

Warning

It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python’s AST compiler.由于Python的AST编译器中的堆栈深度限制,在编译到AST对象时,可能会使用足够大/复杂的字符串使Python解释器崩溃。

Changed in version 3.2: 在3.2版中更改:Allowed use of Windows and Mac newlines. 允许使用Windows和Mac新行。Also, input in 'exec' mode does not have to end in a newline anymore. 此外,'exec'模式下的输入不必再以换行结束。Added the optimize parameter.添加了optimize参数。

Changed in version 3.5: 在3.5版中更改:Previously, TypeError was raised when null bytes were encountered in source.以前,在source中遇到空字节时会引发TypeError

New in version 3.8: 在3.8版中新增:ast.PyCF_ALLOW_TOP_LEVEL_AWAIT can now be passed in flags to enable support for top-level await, async for, and async with.现在可以传入标志,以支持顶级awaitasync forasync with

classcomplex([real[, imag]])

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. 返回值为real+imag*1j的复数,或将字符串或数字转换为复数。If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. 如果第一个参数是字符串,它将被解释为一个复数,并且必须在不使用第二个参数的情况下调用该函数。The second parameter can never be a string. 第二个参数永远不能是字符串。Each argument may be any numeric type (including complex). 每个参数可以是任何数字类型(包括复数)。If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. 如果省略imag,它默认为零,构造函数充当intfloat等数字转换。If both arguments are omitted, returns 0j.如果两个参数都被省略,则返回0j

For a general Python object x, complex(x) delegates to x.__complex__(). 对于一般Python对象xcomplex(x)委托给x.__complex__()If __complex__() is not defined then it falls back to __float__(). 如果没有定义__complex__(),那么它将返回到__float__()If __float__() is not defined then it falls back to __index__().如果未定义__float__()则返回到__index__()

Note

When converting from a string, the string must not contain whitespace around the central + or - operator. 从字符串转换时,字符串的中心+-运算符周围不得包含空格。For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.例如,complex('1+2j')可以,但complex('1 + 2j')会引发ValueError

The complex type is described in Numeric Types — int, float, complex.复数类型在数字类型——int、float、complex有所描述。

Changed in version 3.6: 在3.6版中更改:Grouping digits with underscores as in code literals is allowed.允许将带有下划线的数字分组为代码文本。

Changed in version 3.8: 在3.8版中更改:Falls back to __index__() if __complex__() and __float__() are not defined.如果未定义__complex__()__float__(),则返回到__index__()

delattr(object, name)

This is a relative of setattr(). 这是setattr()的一个亲戚。The arguments are an object and a string. 参数是一个对象和一个字符串。The string must be the name of one of the object’s attributes. 字符串必须是对象属性之一的名称。The function deletes the named attribute, provided the object allows it. 如果对象允许,该函数将删除命名属性。For example, delattr(x, 'foobar') is equivalent to del x.foobar.例如,delattr(x, 'foobar')相当于del x.foobar

classdict(**kwarg)
classdict(mapping, **kwarg)
classdict(iterable, **kwarg)

Create a new dictionary. 创建一个新字典。The dict object is the dictionary class. dict对象是字典类。See dict and Mapping Types — dict for documentation about this class.有关此类的文档,请参阅dict映射类型-dict

For other containers see the built-in list, set, and tuple classes, as well as the collections module.对于其他容器,请参阅内置的listsettuple类,以及collections模块。

dir([object])

Without arguments, return the list of names in the current local scope. 返回当前作用域中不带本地参数的列表。With an argument, attempt to return a list of valid attributes for that object.使用参数,尝试返回该对象的有效属性列表。

If the object has a method named __dir__(), this method will be called and must return the list of attributes. 如果对象有一个名为__dir__()的方法,则将调用此方法,并且必须返回属性列表。This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.这允许实现自定义__getattr__()__getattribute__()函数的对象自定义dir()报告其属性的方式。

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. 如果对象不提供__dir__(),则函数会尽最大努力从该对象的__dict__属性(如果已定义)和类型对象收集信息。The resulting list is not necessarily complete and may be inaccurate when the object has a custom __getattr__().结果列表不一定完整,当对象具有自定义的__getattr__()时,结果列表可能不准确。

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:默认的dir()机制对不同类型的对象表现不同,因为它试图生成最相关的信息,而不是完整的信息:

  • If the object is a module object, the list contains the names of the module’s attributes.如果对象是模块对象,则列表包含模块属性的名称。

  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.如果对象是类型或类对象,则列表包含其属性的名称,并递归地包含其基的属性的名称。

  • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.否则,该列表将包含对象的属性名称、其类的属性名称以及其类的基类的递归属性。

The resulting list is sorted alphabetically. 结果列表按字母顺序排序。For example:例如:

>>> import struct
>>> dir() # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module
['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']

Note

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. 由于提供dir()主要是为了方便在交互提示下使用,因此它尝试提供一组有趣的名称,而不是提供严格或一致定义的名称,而且其详细行为可能会在不同版本中发生变化。For example, metaclass attributes are not in the result list when the argument is a class.例如,当参数是类时,元类属性不在结果列表中。

divmod(a, b)

Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. 取两个(非复数)数作为参数,在使用整数除法时返回一对由它们的商和余数组成的数。With mixed operand types, the rules for binary arithmetic operators apply. 对于混合操作数类型,二进制算术运算符的规则适用。For integers, the result is the same as (a // b, a % b). 对于整数,结果与(a // b, a % b)相同。For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. 对于浮点数,结果是(q, a % b),其中q通常是math.floor(a / b),但可能小于1。In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).在任何情况下,q * b + a % ba非常接近,如果a % b非零,则其符号与b相同,且0 <= abs(a % b) < abs(b)

enumerate(iterable, start=0)

Return an enumerate object. 返回枚举对象。iterable must be a sequence, an iterator, or some other object which supports iteration. iterable必须是序列、迭代器或其他支持迭代的对象。The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.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')]

Equivalent to:相当于:

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

The arguments are a string and optional globals and locals. 参数是字符串和可选的全局变量和局部变量。If provided, globals must be a dictionary. 如果提供,globals必须是字典。If provided, locals can be any mapping object.如果提供了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. expression参数作为Python表达式(从技术上讲,是一个条件列表)进行解析和计算,使用globalslocals字典作为全局和局部名称空间。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. 如果globals字典存在且不包含键__builtins__的值,则在解析expression之前,会在该键下插入对内置模块builtins字典的引用。That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to eval(). 这样,你就可以通过在将__builtins__字典传递给eval()之前将其插入到globals变量中来控制哪些内置函数可以被执行的代码使用。If the locals dictionary is omitted it defaults to the globals dictionary. 如果省略了locals字典,则默认为globals字典。If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. 如果省略了这两个字典,则在调用eval()的环境中使用globals变量和locals变量执行表达式。Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.注意,eval()无权访问封闭环境中的嵌套作用域(非局部变量)。

The return value is the result of the evaluated expression. 返回值是计算表达式的结果。Syntax errors are reported as exceptions. 语法错误报告为异常。Example:例子:

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

This function can also be used to execute arbitrary code objects (such as those created by compile()). 此函数还可用于执行任意代码对象(例如由compile()创建的对象)。In this case, pass a code object instead of a string. 在本例中,传递代码对象而不是字符串。If the code object has been compiled with 'exec' as the mode argument, eval()'s return value will be None.如果代码对象以'exec'作为mode参数进行编译,eval()的返回值将为None

Hints: dynamic execution of statements is supported by the exec() function. 提示:exec()函数支持语句的动态执行。The globals() and locals() functions return the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().globals()locals()函数分别返回当前的全局和局部字典,这可能有助于传递给eval()exec()使用。

If the given source is a string, then leading and trailing spaces and tabs are stripped.如果给定的源是一个字符串,那么前导空格和尾随空格以及制表符将被剥离。

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.请参阅ast.literal_eval(),了解一个函数,该函数可以安全地使用只包含文字的表达式计算字符串。

Raises an auditing event exec with the code object as the argument. 以代码对象作为参数引发审核事件execCode compilation events may also be raised.还可能引发代码编译事件。

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

This function supports dynamic execution of Python code. 此函数支持Python代码的动态执行。object must be either a string or a code object. object必须是字符串或代码对象。If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). 如果它是一个字符串,该字符串将被解析为一组Python语句,然后执行(除非出现语法错误)。1 If it is a code object, it is simply executed. 如果它是一个代码对象,则只需执行它。In all cases, the code that’s executed is expected to be valid as file input (see the section File input in the Reference Manual). 在所有情况下,执行的代码都应作为文件输入有效(参见参考手册中的文件输入一节)。Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. 请注意,nonlocalyieldreturn语句不能在函数定义之外使用,甚至不能在传递给exec()函数的代码上下文中使用。The return value is None.返回值为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 (and not a subclass of dictionary), which will be used for both the global and the local variables. 如果只提供globals,那么它必须是一个dictionary(而不是dictionary的子类),它将用于全局变量和局部变量。If globals and locals are given, they are used for the global and local variables, respectively. 如果给定了globals变量和locals变量,则它们分别用于全局变量和局部变量。If provided, locals can be any mapping object. 如果提供,locals变量可以是任何映射对象。Remember that at the 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.如果exec获得两个单独的对象,即golbals对象和locals对象,那么代码将像嵌入类定义一样执行。

If the globals dictionary 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. 如果globals字典不包含键__builtins__的值,则在该键下插入对内置模块builtins字典的引用。That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().通过这种方式,您可以通过在将自己的__builtins__字典传递给exec()之前将其插入globals,来控制哪些内置代码可用于执行的代码。

Raises an auditing event exec with the code object as the argument. 以代码对象作为参数引发审核事件execCode compilation events may also be raised.还可能引发代码编译事件。

Note

The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().内置函数globals()locals()分别返回当前的全局和局部字典,这可能有助于将其作为第二个和第三个参数传递给exec()

Note

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. 默认locals变量的作用如下面函数locals()所述:不应尝试修改默认locals变量字典。Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.如果需要在函数exec()返回后查看代码对locals变量的影响,请传递一个显式locals变量字典。

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable的那些元素构造一个迭代器,对于这些元素,函数返回trueiterable may be either a sequence, a container which supports iteration, or an iterator. iterable可以是序列、支持迭代的容器或迭代器。If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.如果functionNone,则假定标识函数,即删除iterable中所有为false的元素。

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.请注意,如果函数不是None,则filter(function, iterable)等价于生成器表达式(item for item in iterable if function(item)),如果函数是None,则filter(function, iterable)等价于生成器表达式(item for item in iterable if item)

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.有关返回iterable元素的互补函数,请参阅itertools.filterfalse(),该函数返回false

classfloat([x])

Return a floating point number constructed from a number or string x.返回由数字或字符串x构造的浮点数。

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. 如果参数是字符串,它应该包含一个十进制数,可以选择前面加一个符号,也可以选择嵌入空格。The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. 可选符号可以是'+''-''+'号对生成的值没有影响。The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. 参数也可以是表示NaN(非数字)的字符串,也可以是正无穷大或负无穷大。More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:更准确地说,删除前导和尾随空白字符后,输入必须符合以下语法:


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

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. 这里floatnumber是Python浮点文本的形式,用浮点文本描述。Case is not significant, so, for example, “inf”, “Inf”, “INFINITY”, and “iNfINity” are all acceptable spellings for positive infinity.大小写不重要,因此,例如,“inf”、“Inf”、“INFINITY”和“iNfINity”都是正无穷的可接受拼写。

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. 否则,如果参数是整数或浮点数,则返回具有相同值(在Python的浮点精度内)的浮点数。If the argument is outside the range of a Python float, an OverflowError will be raised.如果参数超出Python浮点值的范围,则会引发OverflowError错误。

For a general Python object x, float(x) delegates to x.__float__(). 对于一般的Python对象xfloat(x)将委托给x.__float__()If __float__() is not defined then it falls back to __index__().如果未定义__float__()则返回到__index__()

If no argument is given, 0.0 is returned.如果没有给出参数,则返回0.0

Examples:例如:

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

The float type is described in Numeric Types — int, float, complex.浮点类型在数字类型——int、float、complex中描述。

Changed in version 3.6: 在3.6版中更改:Grouping digits with underscores as in code literals is allowed.允许将带有下划线的数字分组为代码文本。

Changed in version 3.7: 在3.7版中更改:x is now a positional-only parameter.现在是一个仅用于位置的参数。

Changed in version 3.8: 在3.8版中更改:Falls back to __index__() if __float__() is not defined.如果未定义__float__(),则返回到__index__()

format(value[, format_spec])

Convert a value to a “formatted” representation, as controlled by format_spec. value转换为“格式化”表示,由format_spec控制。The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.format_spec的解释将取决于值参数的类型;但是,大多数内置类型都使用标准格式语法:格式规范迷你语言

The default format_spec is an empty string which usually gives the same effect as calling str(value).默认format_spec是一个空字符串,通常与调用str(value)具有相同的效果。

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. format(value, format_spec)的调用被转换为type(value).__format__(value, format_spec),在搜索值的__format__()方法时绕过实例字典。A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.如果方法搜索到达objectformat_spec为非空,或者格式规格或返回值不是字符串,则会引发TypeError异常。

Changed in version 3.4: 在3.4版中更改:object().__format__(format_spec) raises TypeError if format_spec is not an empty string.如果format_spec不是空字符串,object().__format__(format_spec)将引发TypeError

classfrozenset([iterable])

Return a new frozenset object, optionally with elements taken from iterable. 返回一个新的frozenset对象,可以选择从iterable中获取元素。frozenset is a built-in class. frozenset是一个内置类。See frozenset and Set Types — set, frozenset for documentation about this class.有关此类的文档,请参阅frozensetSet-Types-Set,frozenset

For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.对于其他容器,请参阅内置的setlisttupledict类,以及collections模块。

getattr(object, name[, default])

Return the value of the named attribute of object. 返回object的命名属性的值。name must be a string. name必须是字符串。If the string is the name of one of the object’s attributes, the result is the value of that attribute. 如果字符串是对象属性之一的名称,则结果是该属性的值。For example, getattr(x, 'foobar') is equivalent to x.foobar. 例如,getattr(x, 'foobar')相当于x.foobarIf the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.如果命名属性不存在,则返回default(如果提供),否则将引发AttributeError

Note

Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with getattr().由于私有名称损坏发生在编译时,因此必须手动损坏私有属性(带有两个前导下划线的属性)的名称,以便使用getattr()检索它。

globals()

Return the dictionary implementing the current module namespace. 返回实现当前模块命名空间的字典。For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.对于函数中的代码,这是在定义函数时设置的,并且无论在何处调用函数都保持不变。

hasattr(object, name)

The arguments are an object and a string. 参数是一个对象和一个字符串。The result is True if the string is the name of one of the object’s attributes, False if not. 如果字符串是对象属性之一的名称,则结果为True,否则为False(This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)(这是通过调用getattr(object, name)并查看它是否引发AttributeError来实现的。)

hash(object)

Return the hash value of the object (if it has one). 返回对象的哈希值(如果有)。Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. 散列值是整数。它们用于在字典查找过程中快速比较字典键。Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).比较相等的数值具有相同的哈希值(即使它们的类型不同,如1和1.0)。

Note

For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine. 对于具有自定义__hash__()方法的对象,请注意,hash()会根据主机的位宽度截断返回值。See __hash__() for details.有关详细信息,请参阅__hash__()

help([object])

Invoke the built-in help system. 调用内置的帮助系统。(This function is intended for interactive use.) (此功能用于交互使用。)If no argument is given, the interactive help system starts on the interpreter console. 如果没有给出任何参数,交互式帮助系统将在口译员控制台上启动。If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. 如果参数是字符串,则该字符串将作为模块、函数、类、方法、关键字或文档主题的名称进行查找,并在控制台上打印帮助页面。If the argument is any other kind of object, a help page on the object is generated.如果参数是任何其他类型的对象,则会生成有关该对象的帮助页面。

Note that if a slash(/) appears in the parameter list of a function when invoking help(), it means that the parameters prior to the slash are positional-only. 请注意,如果调用help()时函数的参数列表中出现斜杠(/),则表示斜杠之前的参数仅为位置参数。For more info, see the FAQ entry on positional-only parameters.有关更多信息,请参阅仅位置参数的常见问题解答条目

This function is added to the built-in namespace by the site module.此函数由site模块添加到内置名称空间中。

Changed in version 3.4: 在3.4版中更改:Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.pydocinspect的更改意味着可调用项的报告签名现在更加全面和一致。

hex(x)

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. 将整数转换为前缀为“0x”的小写十六进制字符串。If x is not a Python int object, it has to define an __index__() method that returns an integer. 如果x不是Python int对象,那么它必须定义一个返回整数的__index__()方法。Some examples:例如:

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

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:如果要将整数转换为带前缀的大写或小写十六进制字符串,可以使用以下任一方法:

>>> '%#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')

See also format() for more information.有关更多信息,请参阅format()

See also int() for converting a hexadecimal string to an integer using a base of 16.另请参见int(),了解如何使用基数16将十六进制字符串转换为整数。

Note

To obtain a hexadecimal string representation for a float, use the float.hex() method.要获取浮点的十六进制字符串表示形式,请使用float.hex()方法。

id(object)

Return the “identity” of an object. 返回对象的“标识”。This is an integer which is guaranteed to be unique and constant for this object during its lifetime. 这是一个整数,保证该对象在其生命周期内唯一且恒定。Two objects with non-overlapping lifetimes may have the same id() value.生命周期不重叠的两个对象可能具有相同的id()值。

CPython implementation detail:实施细节: This is the address of the object in memory.这是内存中对象的地址。

Raises an auditing event builtins.id with argument id.引发具有参数id审核事件builtins.id

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. 如果存在prompt参数,则将其写入标准输出,而不带尾随换行符。The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. 然后,函数从输入中读取一行,将其转换为字符串(去掉尾随的换行符),并返回该字符串。When EOF is read, EOFError is raised. 当读取EOF时,EOFError升高。Example:例如:

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

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.如果已加载readline模块,则input()将使用它提供详细的行编辑和历史记录功能。

Raises an auditing event builtins.input with argument prompt before reading input在读取输入之前引发带有参数prompt审核事件builtins.input

Raises an auditing event builtins.input/result with the result after successfully reading input.在成功读取输入后,使用结果引发审核事件builtins.input/result

classint([x])
classint(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. 返回一个由数字或字符串x构造的整数对象,如果没有参数,则返回0If x defines __int__(), int(x) returns x.__int__(). 如果x定义了__int__(),则int(x)返回x.__int__()If x defines __index__(), it returns x.__index__(). 如果x定义了__index__(),它将返回x.__index__()If x defines __trunc__(), it returns x.__trunc__(). 如果x定义了__trunc__(),它将返回x.__trunc__()For floating point numbers, this truncates towards zero.对于浮点数,它会向零截断。

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. 如果x不是一个数字,或者如果给定了base,那么x必须是一个字符串、bytesbytearray实例,以基数表示整数文本Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. 或者,文本前面可以加+-(中间没有空格)并用空格包围。A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. base-n文本由数字0到n-1组成,az(或AZ)的值为10到35。The default base is 10. 默认base为10。The allowed values are 0 and 2–36. 允许值为0和2-36。Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base-2、-8和-16文本可以选择性地以0b/0B0o/0O0x/0X作为前缀,就像代码中的整数文本一样。Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).Base 0的意思是准确地解释为代码文本,因此实际的Base是2、8、10或16,因此int('010', 0)是不合法的,而int('010')是合法的,int('010', 8)也是合法的。

The integer type is described in Numeric Types — int, float, complex.整数类型在数字类型——int、float、complex中描述。

Changed in version 3.4: 在3.4版中更改:If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. 如果base不是int的实例,并且base对象有一个base.__index__方法,调用该方法以获取基数的整数。Previous versions used base.__int__ instead of base.__index__.以前的版本使用base.__int__而不是base.__index__

Changed in version 3.6: 在3.6版中更改:Grouping digits with underscores as in code literals is allowed.允许将带有下划线的数字分组为代码文本。

Changed in version 3.7: 在3.7版中更改:x is now a positional-only parameter.x现在是一个仅用于位置的参数。

Changed in version 3.8: 在3.8版中更改:Falls back to __index__() if __int__() is not defined.如果未定义__int__(),则返回到__index__()

isinstance(object, classinfo)

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. 如果object参数是classinfo参数或其(直接、间接或虚拟)子类的实例,则返回TrueIf object is not an object of the given type, the function always returns False. 如果object不是给定类型的对象,函数总是返回FalseIf classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, return True if object is an instance of any of the types. 如果classinfo是类型对象的元组(或递归地,其他此类元组)或多个类型的联合类型,则如果object是任何类型的实例,则返回TrueIf classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.如果classinfo不是类型或类型的元组,则会引发TypeError异常。

Changed in version 3.10: 在3.10版中更改:classinfo can be a Union Type.可以是联合类型

issubclass(class, classinfo)

Return True if class is a subclass (direct, indirect, or virtual) of classinfo. 如果classclassinfo的子类(直接、间接或虚拟),则返回TrueA class is considered a subclass of itself. 类被认为是其自身的一个子类。classinfo may be a tuple of class objects or a Union Type, in which case return True if class is a subclass of any entry in classinfo. classinfo可以是类对象的元组或联合类型,在这种情况下,如果classclassinfo中任何项的子类,则返回TrueIn any other case, a TypeError exception is raised.在任何其他情况下,都会引发TypeError异常。

Changed in version 3.10: 在3.10版中更改:classinfo can be a Union Type.classinfo可以是联合类型

iter(object[, sentinel])

Return an iterator object. 返回一个迭代器对象。The first argument is interpreted very differently depending on the presence of the second argument. 根据第二个参数的存在,第一个参数的解释非常不同。Without a second argument, object must be a collection object which supports the iterable protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). 如果没有第二个参数,object必须是支持iterable协议的集合对象(__iter__()方法),或者它必须支持sequence协议(__getitem__()方法,整数参数从0开始)。If it does not support either of those protocols, TypeError is raised. 如果它不支持这两种协议中的任何一种,则会引发TypeErrorIf the second argument, sentinel, is given, then object must be a callable object. 如果给出了第二个参数sentinel,则object必须是可调用的对象。The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.在本例中创建的迭代器将调用object,每次调用其__next__()方法时不带任何参数;如果返回的值等于sentinel,则将引发StopIteration,否则将返回该值。

See also Iterator Types.另请参见迭代器类型

One useful application of the second form of iter() is to build a block-reader. 第二种形式的iter()的一个有用应用是构建块读取器。For example, reading fixed-width blocks from a binary database file until the end of file is reached:例如,从二进制数据库文件中读取固定宽度的块,直到到达文件末尾:

from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), b''):
process_block(block)
len(s)

Return the length (the number of items) of an object. 返回对象的长度(项目数)。The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).参数可以是序列(如字符串、字节、元组、列表或范围)或集合(如字典、集合或冻结集合)。

CPython implementation detail:CPython实施细节: len raises OverflowError on lengths larger than sys.maxsize, such as range(2 ** 100).len在大于sys.maxsize的长度上引发OverflowError,例如range(2 ** 100)

classlist([iterable])

Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.list不是一个函数,而是一个可变的序列类型,如列表序列类型 - 列表、元组和范围中所述。

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. 在函数块中而不是在类块中调用自由变量时,它由locals()返回。Note that at the module level, locals() and globals() are the same dictionary.请注意,在模块级别,locals()globals()是同一个字典。

Note

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.本词典的内容不得修改;更改可能不会影响解释器使用的局部变量和自由变量的值。

map(function, iterable, ...)

Return an iterator that applies function to every item of iterable, yielding the results. 返回一个迭代器,该迭代器将function应用于iterable的每个项,并生成结果。If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. 如果传递了额外的iterable参数,则function必须接受这么多参数,并并行应用于所有iterable中的项。With multiple iterables, the iterator stops when the shortest iterable is exhausted. 对于多个iterable,迭代器在最短iterable耗尽时停止。For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().有关函数输入已排列为参数元组的情况,请参阅itertools.starmap()

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

Return the largest item in an iterable or the largest of two or more arguments.返回可迭代对象中最大的项,或两个或多个参数中最大的一个。

If one positional argument is provided, it should be an iterable. 如果提供了一个位置参数,那么它应该是一个可迭代对象。The largest item in the iterable is returned. 返回可迭代对象中最大的项目。If two or more positional arguments are provided, the largest of the positional arguments is returned.如果提供了两个或多个位置参数,则返回最大的位置参数。

There are two optional keyword-only arguments. 有两个可选的纯关键字参数。The key argument specifies a one-argument ordering function like that used for list.sort(). key参数指定一个单参数排序函数,类似于list.sort()所使用的函数。The default argument specifies an object to return if the provided iterable is empty. 如果提供的iterable为空,则default参数指定要返回的对象。If the iterable is empty and default is not provided, a ValueError is raised.如果iterable为空且未提供default,则会引发ValueError

If multiple items are maximal, the function returns the first one encountered. 如果多个项是最大的,则函数返回遇到的第一个项。This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).这与其他保持排序稳定性的工具一致,比如sorted(iterable, key=keyfunc, reverse=True)[0]heapq.nlargest(1, iterable, key=keyfunc)

New in version 3.4: 在3.4版中新增:The default keyword-only argument.default是纯关键字参数。

Changed in version 3.8: 在3.8版中更改:The key can be None.key可以是None

classmemoryview(object)

Return a “memory view” object created from the given argument. 返回根据给定参数创建的“内存视图”对象。See Memory Views for more information.有关更多信息,请参阅内存视图

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

Return the smallest item in an iterable or the smallest of two or more arguments.返回可迭代对象中的最小项或两个或多个参数中的最小项。

If one positional argument is provided, it should be an iterable. 如果提供了一个位置参数,那么它应该是一个可迭代对象The smallest item in the iterable is returned. 返回iterable中最小的项。If two or more positional arguments are provided, the smallest of the positional arguments is returned.如果提供了两个或多个位置参数,则返回最小的位置参数。

There are two optional keyword-only arguments. 有两个可选的纯关键字参数。The key argument specifies a one-argument ordering function like that used for list.sort(). 键参数指定一个单参数排序函数,类似于list.sort()所使用的函数。The default argument specifies an object to return if the provided iterable is empty. 如果提供的可迭代对象为空,则default参数指定要返回的对象。If the iterable is empty and default is not provided, a ValueError is raised.如果可迭代对象为空且未提供default,则会引发ValueError

If multiple items are minimal, the function returns the first one encountered. 如果多个项目最少,函数将返回遇到的第一个项目。This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc).这与其他保持排序稳定性的工具一致,比如sorted(iterable, key=keyfunc)[0]heapq.nsmallest(1, iterable, key=keyfunc)

New in version 3.4: 在3.4版中新增:The default keyword-only argument.default是纯关键字参数。

Changed in version 3.8: 在3.8版中更改:The key can be None.key可以是None

next(iterator[, default])

Retrieve the next item from the iterator by calling its __next__() method. 通过调用迭代器__next__()方法从迭代器中检索下一项。If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.如果给定default,则在迭代器耗尽时返回,否则将引发StopIteration

classobject

Return a new featureless object. 返回一个新的无特征对象。object is a base for all classes. 是所有类的基础。It has methods that are common to all instances of Python classes. 它具有Python类的所有实例所共有的方法。This function does not accept any arguments.此函数不接受任何参数。

Note

object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.没有__dict__,因此无法将任意属性指定给object类的实例。

oct(x)

Convert an integer number to an octal string prefixed with “0o”. 将整数转换为以“0o”为前缀的八进制字符串。The result is a valid Python expression. 结果是一个有效的Python表达式。If x is not a Python int object, it has to define an __index__() method that returns an integer. 如果x不是Python int对象,那么它必须定义一个返回整数的__index__()方法。For example:例如:

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

If you want to convert an integer number to an octal string either with the prefix “0o” or not, you can use either of the following ways.如果要将整数转换为八进制字符串(无论是否带有前缀“0o”),可以使用以下任一方法。

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

See also format() for more information.有关更多信息,请参阅format()

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

Open file and return a corresponding file object. 打开file并返回相应的文件对象If the file cannot be opened, an OSError is raised. 如果无法打开文件,则会引发OSErrorSee Reading and Writing Files for more examples of how to use this function.有关如何使用此函数的更多示例,请参阅读写文件

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. file是一个类似路径的对象,提供要打开的文件的路径名(绝对或相对于当前工作目录)或要包装的文件的整数文件描述符。(If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to False.)(如果给定了文件描述符,则在关闭返回的I/O对象时关闭该描述符,除非closefd设置为False。)

mode is an optional string that specifies the mode in which the file is opened. 是一个可选字符串,指定打开文件的模式。It defaults to 'r' which means open for reading in text mode. 默认为'r',意思是在文本模式下打开阅读。Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). 其他常用值包括'w'表示写入(如果文件已经存在,则截断文件),'x'表示独占创建,以及'a'表示追加(在某些Unix系统上,这意味着所有写入操作都会追加到文件的末尾,而不管当前寻道位置如何)。In text mode, if encoding is not specified the encoding used is platform-dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. 在文本模式下,如果未指定encoding,则使用的编码取决于平台:将调用locale.getpreferredencoding(False)以获取当前的语言环境编码。(For reading and writing raw bytes use binary mode and leave encoding unspecified.) (对于读取和写入原始字节,请使用二进制模式,并保留未指定的encoding。)The available modes are:可用的模式有:

Character字符

Meaning含义

'r'

open for reading (default)打开阅读(默认)

'w'

open for writing, truncating the file first打开以进行写入,首先截断文件

'x'

open for exclusive creation, failing if the file already exists打开以独占方式创建,如果文件已存在,则失败

'a'

open for writing, appending to the end of file if it exists打开进行写入,如果文件存在,则追加到文件末尾

'b'

binary mode二进制模式

't'

text mode (default)文本模式(默认)

'+'

open for updating (reading and writing)开放更新(阅读和写作)

The default mode is 'r' (open for reading text, a synonym of 'rt'). 默认模式为'r'(开放阅读文本,是'rt'的同义词)。Modes 'w+' and 'w+b' open and truncate the file. 模式'w+''w+b'打开并截断文件。Modes 'r+' and 'r+b' open the file with no truncation.模式'r+''r+b'打开文件时不进行截断。

As mentioned in the Overview, Python distinguishes between binary and text I/O. 正如在Python概述中提到的,I/O区分了二进制和二进制。Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. 以二进制模式打开的文件(包括mode参数中的'b')以字节对象的形式返回内容,而不进行任何解码。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.在文本模式下(默认情况下,或当mode参数中包含't'时),文件的内容以str返回,字节首先使用平台相关编码或指定encoding(如果给定)进行解码。

There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. 允许使用一个额外的模式字符'U',它不再有任何效果,并且被视为不推荐使用。It previously enabled universal newlines in text mode, which became the default behavior in Python 3.0. 它以前在文本模式下启用了通用换行符,这成为Python 3.0中的默认行为。Refer to the documentation of the newline parameter for further details.有关newline参数的详细信息,请参阅文档。

Note

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.Python不依赖于底层操作系统的文本文件概念;所有处理都由Python本身完成,因此与平台无关。

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. 传递0以关闭缓冲(仅在二进制模式下允许),传递1以选择行缓冲(仅在文本模式下可用),传递大于1的整数以指示固定大小块缓冲区的字节大小。Note that specifying a buffer size this way applies for binary buffered I/O, but TextIOWrapper (i.e., files opened with mode='r+') would have another buffering. 请注意,这种方式指定缓冲区大小适用于二进制缓冲I/O,但TextIOWrapper(即,以mode='r+'打开的文件)将有另一个缓冲。To disable buffering in TextIOWrapper, consider using the write_through flag for io.TextIOWrapper.reconfigure(). 要在TextIOWrapper中禁用缓冲,考虑使用io.TextIOWrapper.reconfigure()write_through标志。When no buffering argument is given, the default buffering policy works as follows:如果未给出buffering参数,默认缓冲策略的工作方式如下:

  • 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. 二进制文件缓冲在固定大小的块中;缓冲区的大小是通过尝试确定底层设备的“块大小”并返回io.DEFAULT_BUFFER_SIZE的启发式方法来选择的。On many systems, the buffer will typically be 4096 or 8192 bytes long.在许多系统上,缓冲区的长度通常为4096或8192字节。

  • “Interactive” text files (files for which isatty() returns True) use line buffering. “交互式”文本文件(isatty()返回True的文件)使用行缓冲。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. 默认编码依赖于平台(locale.getpreferredencoding()返回的内容),但可以使用Python支持的任何文本编码See the codecs module for the list of supported encodings.有关支持的编码列表,请参阅codecs模块。

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. 有多种标准错误处理程序可用(列在错误处理程序下),但已在codecs.register_error()中注册的任何错误处理名称也有效。The standard names include:标准名称包括:

  • 'strict' to raise a ValueError exception if there is an encoding error. 如果存在编码错误,则引发ValueError异常。The default value of None has the same effect.默认值None具有相同的效果。

  • '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 low surrogate code units ranging from U+DC80 to U+DCFF. 将所有不正确的字节表示为从U+DC80到U+DCFF的低代理代码单元。These surrogate code units will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. 当在写入数据时使用surrogateescape错误处理程序时,这些代理代码单元将被转换回相同的字节。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;.编码不支持的字符将替换为相应的XML字符引用&#nnn;

  • 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences.用Python的反斜杠转义序列替换格式错误的数据。

  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.(仅在写入时支持)将不支持的字符替换为\N{...}转义序列。

newline controls how universal newlines mode works (it only applies to text mode). 控制通用换行符模式的工作方式(它仅适用于文本模式)。It can be None, '', '\n', '\r', and '\r\n'. 它可以是None'''\n''\r''\r\n'It works as follows:其工作原理如下:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. 从流中读取输入时,如果newlineNone,则启用通用换行符模式。Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. 输入中的行可以以'\n''\r''\r\n'结尾,这些行在返回给调用方之前会被翻译成'\n'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. 将输出写入流时,如果newlineNone,则写入的任何'\n'字符都会转换为系统默认的行分隔符os.linesepIf newline is '' or '\n', no translation takes place. 如果newline'''\n',则不会进行转换。If newline is any of the other legal values, any '\n' characters written are translated to the given string.如果newline是任何其他合法值,则写入的任何'\n'字符都将转换为给定字符串。

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. 如果closefdFalse,并且提供了文件描述符而不是文件名,则在关闭文件时,基础文件描述符将保持打开状态。If a filename is given closefd must be True (the default); otherwise, an error will be raised.如果给定文件名,closefd必须为True(默认值);否则,将引发错误。

A custom opener can be used by passing a callable as opener. 可以通过将可调用的作为opener传递来使用自定义开启器。The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). 然后通过使用(fileflags)调用opener来获取文件对象的底层文件描述符。opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).必须返回一个打开的文件描述符(将os.open作为opener传递会产生类似于不传递的功能)。

The newly created file is non-inheritable.新创建的文件不可继承

The following example uses the dir_fd parameter of the os.open() function to open a file relative to a given directory:以下示例使用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. open()函数返回的文件对象的类型取决于模式。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). open()用于以文本模式('w''r''wt''rt'等)打开文件时,它会返回io.TextIOBase(特别是io.TextIOWrapper)的子类。When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. 当使用缓冲以二进制模式打开文件时,返回的类是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. 具体的类各不相同:在读取二进制模式下,它返回一个io.BufferedReader;在写二进制和附加二进制模式下,它返回一个io.BufferedWriter,在读/写模式下,它返回一个io.BufferedRandomWhen buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.当禁用缓冲时,返回原始流,即io.RawIOBase的子类io.FileIO

See also the file handling modules, such as fileinput, io (where open() is declared), os, os.path, tempfile, and shutil.另请参阅文件处理模块,例如fileinputio(其中声明了open())、osos.pathtempfileshutil

Raises an auditing event open with arguments file, mode, flags.引发一个审核事件,该事件使用参数filemodeflags打开。

The mode and flags arguments may have been modified or inferred from the original call.modeflags参数可能已根据原始调用进行了修改或推断。

Changed in version 3.3: 在3.3版中更改:
  • The opener parameter was added.添加了opener参数。

  • The 'x' mode was added.添加了'x'模式。

  • IOError used to be raised, it is now an alias of OSError.以前是被引发的,现在它是OSError的别名。

  • FileExistsError is now raised if the file opened in exclusive creation mode ('x') already exists.现在,如果以独占创建模式('x')打开的文件已存在,则会引发FileExistsError

Changed in version 3.4: 在3.4版中更改:
  • The file is now non-inheritable.该文件现在不可继承。

Deprecated since version 3.4, removed in version 3.10: 从3.4版开始弃用,在3.10版中删除:The 'U' mode.'U'模式

Changed in version 3.5: 在3.5版中更改:
  • If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).如果系统调用被中断,并且信号处理程序没有引发异常,则函数现在会重试系统调用,而不是引发InterruptedError异常(有关原理,请参阅PEP 475)。

  • The 'namereplace' error handler was added.已添加'namereplace'错误处理程序。

Changed in version 3.6: 在3.6版中更改:
ord(c)

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. 给定一个表示一个Unicode字符的字符串,返回一个表示该字符的Unicode代码点的整数。For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. 例如,ord('a')返回整数97ord('€')(欧元符号)返回8364This is the inverse of chr().这与chr()相反。

pow(base, exp[, mod])

Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod). 返回将base幂乘到exp;如果存在mod,则返回将base幂乘到exp,模mod(计算效率高于pow(base, exp) % mod)。The two-argument form pow(base, exp) is equivalent to using the power operator: base**exp.双参数形式pow(base, exp)相当于使用幂运算符:base**exp

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. 对于int操作数,结果的类型与操作数的类型相同(强制后),除非第二个参数为负;在这种情况下,所有参数都转换为float,并传递一个float结果。For example, pow(10, 2) returns 100, but pow(10, -2) returns 0.01. 例如,pow(10, 2)返回100,但pow(10, -2)返回0.01For a negative base of type int or float and a non-integral exponent, a complex result is delivered. 对于intfloat类型的负基和非整数指数,将给出一个复杂的结果。For example, pow(-9, 0.5) returns a value close to 3j.例如,pow(-9, 0.5)返回一个接近3j的值。

For int operands base and exp, if mod is present, mod must also be of integer type and mod must be nonzero. 对于int操作数baseexp,如果mod存在,mod也必须是整数类型,mod必须是非零。If mod is present and exp is negative, base must be relatively prime to mod. 如果mod存在且exp为负,则base必须相对mod为素数。In that case, pow(inv_base, -exp, mod) is returned, where inv_base is an inverse to base modulo mod.在这种情况下,返回pow(inv_base, -exp, mod),其中inv_basebasemod的反比。

Here’s an example of computing an inverse for 38 modulo 97:下面是一个计算3897的逆的例子:

>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True

Changed in version 3.8: 在3.8版中更改:For int operands, the three-argument form of pow now allows the second argument to be negative, permitting computation of modular inverses.对于int操作数,pow的三参数形式现在允许第二个参数为负,从而允许计算模逆。

Changed in version 3.8: 在3.8版中更改:Allow keyword arguments. 允许关键字参数。Formerly, only positional arguments were supported.以前,只支持位置参数。

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

Print objects to the text stream file, separated by sep and followed by end. objects打印到文本流file中,以sep分隔,后跟endsep, end, file, and flush, if present, must be given as keyword arguments.sependfileflush(如果存在)必须作为关键字参数提供。

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. 所有非关键字参数都会像str()一样转换为字符串,并写入流中,以sep分隔,后跟endBoth sep and end must be strings; they can also be None, which means to use the default values. sepend都必须是字符串;它们也可以是None,这意味着使用默认值。If no objects are given, print() will just write end.如果没有objectsprint()将只写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. file参数必须是具有write(string)方法的对象;如果不存在或None,将使用sys.stdoutSince printed arguments are converted to text strings, print() cannot be used with binary mode file objects. 由于打印的参数被转换为文本字符串,print()不能用于二进制模式的文件对象。For these, use file.write(...) instead.对于这些,请使用file.write(...)相反

Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.是否缓冲输出通常由file决定,但如果flush关键字参数为true,则强制刷新流。

Changed in version 3.3: 在3.3版中更改:Added the flush keyword argument.添加了flush关键字参数。

classproperty(fget=None, fset=None, fdel=None, doc=None)

Return a property attribute.返回一个属性。

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.doc为属性创建一个docstring。

A typical use is to define a managed attribute x:典型用途是定义托管属性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.如果cC的实例,c.x将调用getter,c.x=value将调用setter,del c.x将调用deleter。

If given, doc will be the docstring of the property attribute. 如果给定,doc将是property属性的docstring。Otherwise, the property will copy fget’s docstring (if it exists). 否则,该属性将复制fget的docstring(如果存在)。This makes it possible to create read-only properties easily using property() as a decorator:这使得使用property()作为装饰器轻松创建只读属性成为可能:

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.”@property装饰器将voltage()方法转换为同名只读属性的“getter”,并将voltage的docstring设置为“获取当前电压”

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. 属性对象具有gettersetterdeleter方法,这些方法可用作装饰器,用于创建属性的副本,并将相应的访问器函数设置为装饰函数。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.)确保为附加函数指定与原始属性相同的名称(在本例中为x

The returned property object also has the attributes fget, fset, and fdel corresponding to the constructor arguments.返回的属性对象还具有与构造函数参数对应的属性fgetfsetfdel

Changed in version 3.5: 在3.5版中更改:The docstrings of property objects are now writeable.属性对象的docstring现在是可写的。

classrange(stop)
classrange(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.range并不是一个函数,而是一个不可变的序列类型,如Ranges序列类型-列表、元组、范围中所述。

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. 对于许多类型,此函数试图返回一个字符串,当传递给eval()时,该字符串将生成一个具有相同值的对象;否则,表示是一个用尖括号括起来的字符串,其中包含对象类型的名称以及其他信息,通常包括对象的名称和地址。A class can control what this function returns for its instances by defining a __repr__() method.类可以通过定义__repr__()方法来控制此函数为其实例返回的内容。

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).必须是具有__reversed__()方法或支持序列协议的对象(具有从0开始的整数参数的__len__()方法和__getitem__()方法)。

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. 返回小数点后四舍五入到ndigits精度的numberIf ndigits is omitted or is None, it returns the nearest integer to its input.如果ndigits被省略或为None,它将返回最接近其输入的整数。

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). 对于支持round()的内置类型,将值四舍五入到最接近幂减去ndigit的10倍;如果两个倍数相等,则舍入是朝偶数方向进行的(例如,round(0.5)round(-0.5)均为0round(1.5)均为2)。Any integer value is valid for ndigits (positive, zero, or negative). 任何整数值都对ndigit有效(正、零或负)。The return value is an integer if ndigits is omitted or None. 如果省略ndigitsndigitsNone,则返回值为整数。Otherwise, the return value has the same type as number.否则,返回值的类型与number相同。

For a general Python object number, round delegates to number.__round__.对于一般的Python对象numberround委托为number.__round__

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. float的round()行为可能令人惊讶:例如,round(2.675, 2)给出的是2.67,而不是预期的2.68This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. 这不是一个错误:这是因为大多数小数不能精确地表示为浮点。See Floating Point Arithmetic: Issues and Limitations for more information.有关更多信息,请参阅浮点算术:问题和限制

classset([iterable])

Return a new set object, optionally with elements taken from iterable. 返回一个新的set对象,可以选择从iterable中获取元素。set is a built-in class. 是一个内置的类。See set and Set Types — set, frozenset for documentation about this class.有关此类的文档,请参阅set集类型-set、frozenset

For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module.对于其他容器,请参阅内置的frozensetlisttupledict类,以及collections模块。

setattr(object, name, value)

This is the counterpart of getattr(). 这是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.例如,setattr(x, 'foobar', 123)相当于x.foobar = 123

Note

Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to set it with setattr().由于私有名称损坏发生在编译时,因此必须手动损坏私有属性(带有两个前导下划线的属性)的名称,以便使用setattr()对其进行设置。

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

Return a slice object representing the set of indices specified by range(start, stop, step). 返回一个切片对象,表示range(start, stop, step)指定的索引集。The start and step arguments default to None. startstep参数默认为NoneSlice objects have read-only data attributes start, stop, and step which merely return the argument values (or their default). 切片对象具有只读数据属性startstopstep,这些属性仅返回参数值(或其默认值)。They have no other explicit functionality; however, they are used by NumPy and other third-party packages. 它们没有其他明确的功能;但是,NumPy和其他第三方软件包都使用它们。Slice objects are also generated when extended indexing syntax is used. 使用扩展索引语法时,也会生成切片对象。For example: a[start:stop:step] or a[start:stop, i]. 例如,a[start:stop:step]a[start:stop, i]See itertools.islice() for an alternate version that returns an iterator.有关返回迭代器的替代版本,请参阅itertools.islice()

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

Return a new sorted list from the items in iterable.iterable中的项返回一个新的排序列表。

Has two optional arguments which must be specified as keyword arguments.有两个可选参数,必须指定为关键字参数。

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). key指定一个参数的函数,用于从iterable中的每个元素中提取比较键(例如key=str.lower)。The default value is None (compare the elements directly).默认值为None(直接比较元素)。

reverse is a boolean value. 是一个布尔值。If set to True, then the list elements are sorted as if each comparison were reversed.如果设置为True,则列表元素将被排序,就像每个比较都被反转一样。

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.使用functools.cmp_to_key()将旧式cmp函数转换为key函数。

The built-in sorted() function is guaranteed to be stable. 内置的sorted()函数保证是稳定的。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).如果排序保证不改变比较相等的元素的相对顺序,则排序是稳定的——这有助于多次排序(例如,按部门排序,然后按薪资等级排序)。

The sort algorithm uses only < comparisons between items. 排序算法只使用项目之间的<比较。While defining an __lt__() method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented. 虽然定义一个__lt__()方法就足以进行排序,但PEP 8建议实现所有六个丰富的比较This will help avoid bugs when using the same data with other ordering tools such as max() that rely on a different underlying method. 这将有助于避免在将相同的数据与依赖不同底层方法的其他排序工具(如max())一起使用时出现错误。Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the __gt__() method.实现所有六种比较也有助于避免混合类型比较的混淆,混合类型比较可以调用__gt__()方法。

For sorting examples and a brief sorting tutorial, see Sorting HOW TO.有关排序示例和简短的排序教程,请参阅如何排序

@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 Function definitions for details.@staticmethod形式是一个函数装饰器——有关详细信息,请参阅函数定义

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). 静态方法既可以在类(如C.f())上调用,也可以在实例(如C().f())上调用。Moreover, they can be called as regular functions (such as f()).此外,它们可以被称为正则函数(如f())。

Static methods in Python are similar to those found in Java or C++. Python中的静态方法类似于Java或C++中的静态方法。Also, see classmethod() for a variant that is useful for creating alternate class constructors.另外,请参阅classmethod(),了解一个用于创建备用类构造函数的变量。

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. 与所有装饰器一样,也可以将staticmethod作为常规函数调用,并对其结果进行处理。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:对于这些情况,请使用以下习语:

def regular_function():
...
class C:
method = staticmethod(regular_function)

For more information on static methods, see The standard type hierarchy.有关静态方法的更多信息,请参阅标准类型层次结构

Changed in version 3.10: 在3.10版中更改:Static methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__), have a new __wrapped__ attribute, and are now callable as regular functions.静态方法现在继承了方法属性(__module____name____qualname____doc____annotations__),具有一个新的__wrapped__属性,现在可以作为常规函数调用。

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

Return a str version of object. 返回objectstr版本。See str() for details.有关详细信息,请参阅str()

str is the built-in string class. 是内置的字符串For general information about strings, see Text Sequence Type — str.有关字符串的一般信息,请参阅文本序列类型-str

sum(iterable, /, start=0)

Sums start and the items of an iterable from left to right and returns the total. 从左到右对startiterable的项求和,并返回总数。The iterable’s items are normally numbers, and the start value is not allowed to be a string.iterable的项通常是数字,起始值不允许是字符串。

For some use cases, there are good alternatives to sum(). 对于某些用例,sum()有很好的替代方法。The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). 连接字符串序列的首选快速方法是调用''.join(sequence)To add floating point values with extended precision, see math.fsum(). 要添加具有扩展精度的浮点值,请参阅math.fsum()To concatenate a series of iterables, consider using itertools.chain().要连接一系列可重用项,请考虑使用itertools.chain()

Changed in version 3.8: 在3.8版中更改:The start parameter can be specified as a keyword argument.可以将start参数指定为关键字参数。

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

Return a proxy object that delegates method calls to a parent or sibling class of type. 返回一个代理对象,该对象将方法调用委托给type的父类或同级类。This is useful for accessing inherited methods that have been overridden in a class.这对于访问类中已重写的继承方法很有用。

The object-or-type determines the method resolution order to be searched. object-or-type决定了要搜索的方法解析顺序The search starts from the class right after the type.搜索从type后面的类开始。

For example, if __mro__ of object-or-type is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.例如,如果object-or-type__mro__D -> B -> C -> A -> object,并且type的值是B,则super()搜索C -> A -> object

The __mro__ attribute of the object-or-type lists the method resolution search order used by both getattr() and super(). object-or-type__mro__属性列出getattr()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. 如果第二个参数是对象,则isinstance(obj, type)必须为trueIf the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).如果第二个参数是类型,issubclass(type2, type)必须为true(这对类方法很有用)。

There are two typical use cases for super. 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. 在具有单一继承的类层次结构中,可以使用super引用父类,而无需显式命名它们,从而使代码更易于维护。This use closely parallels the use of super in other programming languages.这种用法与super在其他编程语言中的用法非常相似。

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. 这个用例是Python独有的,在静态编译语言或只支持单一继承的语言中找不到。This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. 这使得实现“菱形图”成为可能,其中多个基类实现相同的方法。Good design dictates that such implementations 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)

In addition to method lookups, super() also works for attribute lookups. 除了方法查找,super()还适用于属性查找。One possible use case for this is calling descriptors in a parent or sibling class.一个可能的用例是在父类或同级类中调用描述符

Note that super() is implemented as part of the binding process for explicit dotted attribute lookups such as super().__getitem__(name). 请注意,super()是作为绑定过程的一部分实现的,用于显式虚线属性查找,例如super().__getitem__(name)It does so by implementing its own __getattribute__() method for searching classes in a predictable order that supports cooperative multiple inheritance. 它通过实现自己的__getattribute__()方法来实现这一点,该方法以支持协作多重继承的可预测顺序搜索类。Accordingly, super() is undefined for implicit lookups using statements or operators such as super()[name].因此,对于使用语句或运算符(如super()[name])的隐式查找,super()是未定义的。

Also note that, aside from the zero argument form, super() is not limited to use inside methods. 还要注意的是,除了零参数形式之外,super()不限于在方法内部使用。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().有关如何使用super()设计协作类的实用建议,请参阅使用super()指南

classtuple([iterable])

Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.tuple不是一个函数,而是一个不可变的序列类型,如元组序列类型-列表、元素和范围中所述。

classtype(object)
classtype(name, bases, dict, **kwds)

With one argument, return the type of an object. 使用一个参数,返回object的类型。The return value is a type object and generally the same object as returned by object.__class__.返回值是一个类型对象,通常与object.__class__返回的对象相同。

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.建议使用isinstance()内置函数来测试对象的类型,因为它考虑了子类。

With three arguments, return a new type object. 使用三个参数,返回一个新的类型对象。This is essentially a dynamic form of the class statement. 这本质上是class语句的一种动态形式。The name string is the class name and becomes the __name__ attribute. name字符串是类名,并成为__name__属性。The bases tuple contains the base classes and becomes the __bases__ attribute; if empty, object, the ultimate base of all classes, is added. bases元组包含基类,并成为__bases__属性;如果为空,则添加所有类的最终基objectThe dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the __dict__ attribute. dict字典包含类主体的属性和方法定义;在成为__dict__之前,它会被复制或包装。The following two statements create identical type objects:以下两条语句创建相同的type对象:

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

See also Type Objects.请参见类型对象

Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually __init_subclass__()) in the same way that keywords in a class definition (besides metaclass) would.提供给三个参数形式的关键字参数被传递到适当的元类机制(通常是__init_subclass__()),传递方式与类定义中的关键字(除了metaclass)相同。

See also Customizing class creation.另请参见自定义类创建

Changed in version 3.6: 在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.不重写type.__new__type的子类可能不再使用单参数形式获取对象的类型。

vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.返回模块、类、实例或任何其他具有__dict__属性的对象的__dict__属性。

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).模块和实例等对象具有可更新的__dict__属性;但是,其他对象可能对其__dict__属性有写限制(例如,类使用types.MappingProxyType来防止直接更新字典)。

Without an argument, vars() acts like locals(). 没有参数,vars()的行为就像locals()Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.注意,由于忽略了对本地字典的更新,因此本地字典仅对读取有用。

A TypeError exception is raised if an object is specified but it doesn’t have a __dict__ attribute (for example, if its class defines the __slots__ attribute).如果指定了一个对象,但该对象没有__dict__属性(例如,如果其类定义了__slots__属性),则会引发TypeError异常。

zip(*iterables, strict=False)

Iterate over several iterables in parallel, producing tuples with an item from each one.并行迭代多个可迭代对象,生成包含可迭代对象中每个项的元组。

Example:

>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')

More formally: zip() returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.更正式地说:zip()返回一个元组迭代器,其中第i个元组包含来自每个参数可迭代对象的第i个元素。

Another way to think of zip() is that it turns rows into columns, and columns into rows. 考虑zip()的另一种方式是,它将行转换为列,将列转换为行。This is similar to transposing a matrix.这类似于转置矩阵

zip() is lazy: The elements won’t be processed until the iterable is iterated on, e.g. by a for loop or by wrapping in a list.zip()是惰性的:在可迭代对象被迭代(例如,通过for循环或包装在list中)之前,元素不会被处理。

One thing to consider is that the iterables passed to zip() could have different lengths; sometimes by design, and sometimes because of a bug in the code that prepared these iterables. 需要考虑的一点是,传递给zip()的可迭代对象可能有不同的长度;有时是出于设计,有时是因为编写这些iterables的代码中存在缺陷。Python offers three different approaches to dealing with this issue:Python提供了三种不同的方法来处理这个问题:

  • By default, zip() stops when the shortest iterable is exhausted. 默认情况下,当最短的可迭代对象用完时,zip()停止。It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:它将忽略较长可迭代对象中的剩余项,将结果截断为最短可迭代对象的长度:

    >>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
    [(0, 'fee'), (1, 'fi'), (2, 'fo')]
  • zip() is often used in cases where the iterables are assumed to be of equal length. 通常用于假定易位长度相等的情况。In such cases, it’s recommended to use the strict=True option. 在这种情况下,建议使用strict=True选项。Its output is the same as regular zip():其输出与常规zip()相同:

    >>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
    [('a', 1), ('b', 2), ('c', 3)]

    Unlike the default behavior, it checks that the lengths of iterables are identical, raising a ValueError if they aren’t:与默认行为不同,它检查可迭代对象的长度是否相同,如果不相同,则会引发ValueError

    >>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True))
    Traceback (most recent call last):
    ...
    ValueError: zip() argument 2 is longer than argument 1

    Without the strict=True argument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.如果没有strict=True参数,任何导致不同长度的可迭代对象的bug都将被沉默,可能会在程序的另一部分表现为难以找到的bug。

  • Shorter iterables can be padded with a constant value to make all the iterables have the same length. 较短的可迭代对象可以用一个常量值填充,以使所有可迭代对象具有相同的长度。This is done by itertools.zip_longest().这是由itertools.zip_longest()完成的。

Edge cases: With a single iterable argument, zip() returns an iterator of 1-tuples. 边缘情形:使用单个iterable参数,zip()返回一个1元组的迭代器。With no arguments, it returns an empty iterator.如果没有参数,它将返回一个空迭代器。

Tips and tricks:小贴士和窍门:

  • The left-to-right evaluation order of the iterables is guaranteed. iterables从左到右的评估顺序是有保证的。This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n, strict=True). 这使得使用zip(*[iter(s)]*n, strict=True)将数据序列聚类为n个长度组成为可能。This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. 这会将same迭代器重复n次,这样每个输出元组都有n次调用迭代器的结果。This has the effect of dividing the input into n-length chunks.这样做的效果是将输入分成n个长度的块。

  • zip() in conjunction with the * operator can be used to unzip a list:zip()*运算符一起可用于解压缩列表:

    >>> x = [1, 2, 3]
    >>> y = [4, 5, 6]
    >>> list(zip(x, y))
    [(1, 4), (2, 5), (3, 6)]
    >>> x2, y2 = zip(*zip(x, y))
    >>> x == list(x2) and y == list(y2)
    True

Changed in version 3.10: 在3.10版中更改:Added the strict argument.添加了strict参数。

__import__(name, globals=None, locals=None, fromlist=(), level=0)

Note

This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().这是日常Python编程中不需要的高级函数,与importlib.import_module()不同。

This function is invoked by the import statement. 此函数由import语句调用。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. 为了改变import语句的语义,可以替换它(通过导入builtins模块并将其分配给内置模块)。但是强烈建议不要这样做,因为使用导入钩子(参见PEP 302)来实现相同的目标通常更简单,并且不会导致假定默认导入实现正在使用的代码出现问题。Direct use of __import__() is also discouraged in favor of importlib.import_module().也不鼓励直接使用__import__()而支持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. 该函数导入模块name,可能会使用给定的globals变量和locals变量来确定如何在包上下文中解释该名称。The fromlist gives the names of objects or submodules that should be imported from the module given by name. fromlist提供了对象或子模块的名称,这些对象或子模块应该从名为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.标准实现根本不使用其locals参数,只使用其globals来确定import语句的包上下文。

level specifies whether to use absolute or relative imports. level指定是使用绝对导入还是相对导入。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).level的正值表示相对于调用__import__()的模块的目录要搜索的父目录数(有关详细信息,请参阅PEP 328)。

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. name变量的形式为package.module时,通常会返回顶级包(直到第一个点的名称),而不是按名称命名的模块。However, when a non-empty fromlist argument is given, the module named by name is returned.但是,当给出非空的fromlist参数时,将返回按name命名的模块。

For example, the statement import spam results in bytecode resembling the following code:例如,import spam语句会产生类似以下代码的字节码:

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

The statement import spam.ham results in this call:import spam.ham语句将导致以下调用:

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.请注意__import__()如何在此处返回顶级模块,因为这是通过import语句绑定到名称的对象。

On the other hand, the statement from spam.ham import eggs, sausage as saus results in另一方面,语句from spam.ham import eggs, sausage as saus导致

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

Here, the spam.ham module is returned from __import__(). 这里,spam.ham模块是从__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().如果只想按名称导入模块(可能在包中),请使用importlib.import_module()

Changed in version 3.3: 在3.3版中更改:Negative values for level are no longer supported (which also changes the default value to 0).level的负值不再受支持(这也会将默认值更改为0)。

Changed in version 3.9: 在3.9版中更改:When the command line options -E or -I are being used, the environment variable PYTHONCASEOK is now ignored.当使用命令行选项-E-I时,环境变量PYTHONCASEOK现在被忽略。

Footnotes

1

Note that the parser only accepts the Unix-style end of line convention. 请注意,解析器只接受Unix风格的行尾约定。If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.如果从文件中读取代码,请确保使用换行符转换模式转换Windows或Mac风格的换行符。