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如果iterable的所有元素都为True
if all elements of the iterable are true (or if the iterable is empty).True
(或者iterable为空),则返回True
。Equivalent to:相当于:def all(iterable):
for element in iterable:
if not element:
return False
return True
-
awaitable
anext
(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这将调用async_iterator的__anext__()
method of async_iterator, returning an awaitable.__anext__()
方法,返回一个awaitable。Awaiting 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如果iterable的任何元素为True
if any element of the iterable is true.True
,则返回True
。If the iterable is empty, return如果iterable为空,则返回False
.False
。Equivalent 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 byrepr()
using\x
,\u
, or\U
escapes.repr()
,返回包含对象的可打印表示形式的字符串,但使用\x
、\u
或\u
转义符转义repr()
返回的字符串中的非ASCII字符。This generates a string similar to that returned by这将生成一个类似于Python 2中repr()
in 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如果x不是Pythonint
object, it has to define an__index__()
method that returns an integer.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')
-
class
bool
([x])¶ Return a Boolean value, i.e. one of返回一个布尔值,即True
orFalse
.True
或False
。x is converted using the standard truth testing procedure.使用标准真值测试程序转换x。If x is false or omitted, this returns如果x为False
; otherwise, it returnsTrue
.False
或省略,则返回False
;否则,它将返回True
。Thebool
class is a subclass ofint
(see Numeric Types — int, float, complex).bool
类是int
的一个子类(参见数值类型-int、float、complex)。It cannot be subclassed further.它不能再细分了。Its only instances are它唯一的实例是False
andTrue
(see Boolean Values).False
和True
(请参见布尔值)。Changed in version 3.7:在3.7版中更改:xis now a positional-only parameter.现在是一个仅用于位置的参数。
-
breakpoint
(*args, **kws)¶ This function drops you into the debugger at the call site.此函数将您放入调用站点的调试器中。Specifically, it calls具体来说,它调用sys.breakpointhook()
, passingargs
andkws
straight through.sys.breakpointhook()
,直接传递args
和kws
。By default,默认情况下,sys.breakpointhook()
callspdb.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 andbreakpoint()
will automatically call that, allowing you to drop into the debugger of choice.sys.breakpointhook()
设置为其他函数,breakpoint()
将自动调用该函数,从而允许您进入所选的调试器。Raises an auditing event使用参数builtins.breakpoint
with argumentbreakpointhook
.breakpointhook
引发审核事件builtins.breakpoint
。New in version 3.7.3.7版新增。
-
class
bytearray
([source[, encoding[, errors]]]) Return a new array of bytes.返回一个新的字节数组。Thebytearray
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;如果它是一个string,您还必须给出编码(以及可选的error)参数;然后,bytearray()
then converts the string to bytes usingstr.encode()
.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如果它是一个iterable,那么它必须是0 <= x < 256
, which are used as the initial contents of the array.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.另请参见二进制序列类型——字节、字节数组、内存视图和字节数组对象。
-
class
bytes
([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 ofbytearray
– it has the same non-mutating methods and the same indexing and slicing behavior.bytes
是bytearray
的一个不可变版本——它具有相同的非变异方法和相同的索引和切片行为。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如果object参数显示为可调用,则返回True
if the object argument appears callable,False
if not.True
,否则返回False
。If this returns如果返回True
, it is still possible that a call fails, but if it isFalse
, 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'
, whilechr(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)。如果i超出该范围,则会引发ValueError
will be raised if i is outside that range.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 asC().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()
oreval()
.exec()
或eval()
执行。source can either be a normal string, a byte string, or an AST object.source可以是普通字符串、字节字符串或AST对象。Refer to the有关如何使用AST对象的信息,请参阅ast
module documentation for information on how to work with AST objects.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 (filename参数应该给出读取代码的文件;如果不是从文件中读取,则传递一些可识别的值(通常使用'<string>'
is commonly used).'<string>'
。The mode argument specifies what kind of code must be compiled; it can bemode参数指定必须编译的代码类型;如果source由一系列语句组成,则可以是'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 thanNone
will be printed).'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.可选参数flags和dont_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, withPyCF_
prefix.ast
模块中找到,带有PyCF_
前缀。The argument optimize specifies the optimization level of the compiler; the default value of参数optimize指定编译器的优化级别;默认值-1
selects the optimization level of the interpreter as given by-O
options.-1
选择解释器的优化级别,如-O
选项所示。Explicit levels are显式级别为0
(no optimization;__debug__
is true),1
(asserts are removed,__debug__
is false) or2
(docstrings are removed too).0
(无优化;__debug__
为true
)、1
(删除断言,__debug__
为false
)或2
(也删除文档字符串)。This function raises如果编译的源无效,此函数将引发SyntaxError
if the compiled source is invalid, andValueError
if the source contains null bytes.SyntaxError
,如果源包含空字节,则会引发ValueError
。If you want to parse Python code into its AST representation, see如果要将Python代码解析为其AST表示形式,请参阅ast.parse()
.ast.parse()
。Raises an auditing event使用参数compile
with argumentssource
andfilename
.source
和filename
引发审核事件compile
。This 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,以前,在source中遇到空字节时会引发TypeError
was raised when null bytes were encountered in 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
, andasync with
.await
、async for
和async with
。
-
class
complex
([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如果省略imag,它默认为零,构造函数充当int
andfloat
.int
和float
等数字转换。If both arguments are omitted, returns如果两个参数都被省略,则返回0j
.0j
。For a general Python object对于一般Python对象x
,complex(x)
delegates tox.__complex__()
.x
,complex(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, butcomplex('1 + 2j')
raisesValueError
.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 todel x.foobar
.delattr(x, 'foobar')
相当于del x.foobar
。
-
class
dict
(**kwarg) -
class
dict
(mapping, **kwarg) -
class
dict
(iterable, **kwarg) Create a new dictionary.创建一个新字典。Thedict
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
, andtuple
classes, as well as thecollections
module.list
、set
和tuple
类,以及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 waydir()
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 usuallymath.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, ifa % b
is non-zero it has the same sign as b, and0 <= abs(a % b) < abs(b)
.q * b + a % b
与a非常接近,如果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 byenumerate()
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表达式(从技术上讲,是一个条件列表)进行解析和计算,使用globals和locals字典作为全局和局部名称空间。If the globals dictionary is present and does not contain a value for the key如果globals字典存在且不包含键__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key before expression is parsed.__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 toeval()
.__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')
2This 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 beNone
.'exec'
作为mode参数进行编译,eval()
的返回值将为None
。Hints: dynamic execution of statements is supported by the提示:exec()
function.exec()
函数支持语句的动态执行。Theglobals()
andlocals()
functions return the current global and local dictionary, respectively, which may be useful to pass around for use byeval()
orexec()
.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.exec
。Code 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语句,然后执行(除非出现语法错误)。1If 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
, andreturn
statements may not be used outside of function definitions even within the context of code passed to theexec()
function.nonlocal
、yield
和return
语句不能在函数定义之外使用,甚至不能在传递给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如果globals字典不包含键__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key.__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 toexec()
.__builtins__
字典传递给exec()
之前将其插入globals,来控制哪些内置代码可用于执行的代码。Raises an auditing event以代码对象作为参数引发审核事件exec
with the code object as the argument.exec
。Code compilation events may also be raised.还可能引发代码编译事件。Note
The built-in functions内置函数globals()
andlocals()
return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument toexec()
.globals()
和locals()
分别返回当前的全局和局部字典,这可能有助于将其作为第二个和第三个参数传递给exec()
。Note
The default locals act as described for function默认locals变量的作用如下面函数locals()
below: modifications to the default locals dictionary should not be attempted.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的那些元素构造一个迭代器,对于这些元素,函数返回true
。iterable may be either a sequence, a container which supports iteration, or an iterator.iterable可以是序列、支持迭代的容器或迭代器。If function is如果function为None
, the identity function is assumed, that is, all elements of iterable that are false are removed.None
,则假定标识函数,即删除iterable中所有为false
的元素。Note that请注意,如果函数不是filter(function, iterable)
is equivalent to the generator expression(item for item in iterable if function(item))
if function is notNone
and(item for item in iterable if item)
if function isNone
.None
,则filter(function, iterable)
等价于生成器表达式(item for item in iterable if function(item))
,如果函数是None
,则filter(function, iterable)
等价于生成器表达式(item for item in iterable if item)
。See有关返回iterable元素的互补函数,请参阅itertools.filterfalse()
for the complementary function that returns elements of iterable for which function returns false.itertools.filterfalse()
,该函数返回false
。
-
class
float
([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如果参数超出Python浮点值的范围,则会引发OverflowError
will be raised.OverflowError
错误。For a general Python object对于一般的Python对象x
,float(x)
delegates tox.__float__()
.x
,float(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')
-infThe 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版中更改:xis 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默认format_spec是一个空字符串,通常与调用str(value)
.str(value)
具有相同的效果。A call to对format(value, format_spec)
is translated totype(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 reachesobject
and the format_spec is non-empty, or if either the format_spec or the return value are not strings.object
且format_spec为非空,或者格式规格或返回值不是字符串,则会引发TypeError
异常。
-
class
frozenset
([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.frozenset
和Set-Types-Set,frozenset。For other containers see the built-in对于其他容器,请参阅内置的set
,list
,tuple
, anddict
classes, as well as thecollections
module.set
、list
、tuple
和dict
类,以及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 tox.foobar
.getattr(x, 'foobar')
相当于x.foobar
。If the named attribute does not exist, default is returned if provided, otherwise如果命名属性不存在,则返回default(如果提供),否则将引发AttributeError
is raised.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 anAttributeError
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)。
-
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
模块添加到内置名称空间中。
-
hex
(x)¶ Convert an integer number to a lowercase hexadecimal string prefixed with “0x”.将整数转换为前缀为“0x”的小写十六进制字符串。If x is not a Python如果x不是Pythonint
object, it has to define an__index__()
method that returns an integer.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 argumentid
.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,当读取EOF时,EOFError
is raised.EOFError
升高。Example:例如:>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"If the如果已加载readline
module was loaded, theninput()
will use it to provide elaborate line editing and history features.readline
模块,则input()
将使用它提供详细的行编辑和历史记录功能。Raises an auditing event在读取输入之前引发带有参数builtins.input
with argumentprompt
before reading inputprompt
的审核事件builtins.input
Raises an auditing event在成功读取输入后,使用结果引发审核事件builtins.input/result
with the result after successfully reading input.builtins.input/result
。
-
class
int
([x])¶ -
class
int
(x, base=10) Return an integer object constructed from a number or string x, or return返回一个由数字或字符串x构造的整数对象,如果没有参数,则返回0。0
if no arguments are given.If x defines如果x定义了__int__()
,int(x)
returnsx.__int__()
.__int__()
,则int(x)
返回x.__int__()
。If x defines如果x定义了__index__()
, it returnsx.__index__()
.__index__()
,它将返回x.__index__()
。If x defines如果x定义了__trunc__()
, it returnsx.__trunc__()
.__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,如果x不是一个数字,或者如果给定了base,那么x必须是一个字符串、bytes
, orbytearray
instance representing an integer literal in radix base.bytes
或bytearray
实例,以基数表示整数文本。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, withbase-n文本由数字0到n-1组成,a
toz
(orA
toZ
) having values 10 to 35.a
到z
(或A
到Z
)的值为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 withBase-2、-8和-16文本可以选择性地以0b
/0B
,0o
/0O
, or0x
/0X
, as with integer literals in code.0b
/0B
、0o
/0O
或0x
/0X
作为前缀,就像代码中的整数文本一样。Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so thatBase 0的意思是准确地解释为代码文本,因此实际的Base是2、8、10或16,因此int('010', 0)
is not legal, whileint('010')
is, as well asint('010', 8)
.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如果base不是int
and the base object has abase.__index__
method, that method is called to obtain an integer for the base.int
的实例,并且base对象有一个base.__index__
方法,调用该方法以获取基数的整数。Previous versions used以前的版本使用base.__int__
instead ofbase.__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如果object参数是classinfo参数或其(直接、间接或虚拟)子类的实例,则返回True
if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof.True
。If object is not an object of the given type, the function always returns如果object不是给定类型的对象,函数总是返回False
.False
。If classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, return如果classinfo是类型对象的元组(或递归地,其他此类元组)或多个类型的联合类型,则如果object是任何类型的实例,则返回True
if object is an instance of any of the types.True
。If classinfo is not a type or tuple of types and such tuples, a如果classinfo不是类型或类型的元组,则会引发TypeError
exception is raised.TypeError
异常。Changed in version 3.10:在3.10版中更改:classinfocan be a Union Type.可以是联合类型。
-
issubclass
(class, classinfo)¶ Return如果class是classinfo的子类(直接、间接或虚拟),则返回True
if class is a subclass (direct, indirect, or virtual) of classinfo.True
。A class is considered a subclass of itself.类被认为是其自身的一个子类。classinfo may be a tuple of class objects or a Union Type, in which case returnclassinfo可以是类对象的元组或联合类型,在这种情况下,如果class是classinfo中任何项的子类,则返回True
if class is a subclass of any entry in classinfo.True
。In 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如果没有第二个参数,object必须是支持iterable协议的集合对象(__iter__()
method), or it must support the sequence protocol (the__getitem__()
method with integer arguments starting at0
).__iter__()
方法),或者它必须支持sequence协议(__getitem__()
方法,整数参数从0
开始)。If it does not support either of those protocols,如果它不支持这两种协议中的任何一种,则会引发TypeError
is raised.TypeError
。If 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在本例中创建的迭代器将调用object,每次调用其__next__()
method; if the value returned is equal to sentinel,StopIteration
will be raised, otherwise the value will be returned.__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
raisesOverflowError
on lengths larger thansys.maxsize
, such asrange(2 ** 100)
.len
在大于sys.maxsize
的长度上引发OverflowError
,例如range(2 ** 100)
。
-
class
list
([iterable]) Rather than being a function,list
is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.list
不是一个函数,而是一个可变的序列类型,如列表和序列类型 - 列表、元组和范围中所述。
-
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()
andglobals()
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 forlist.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如果iterable为空且未提供default,则会引发ValueError
is raised.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]
andheapq.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 bekey可以是None
.None
。
-
class
memoryview
(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如果可迭代对象为空且未提供default,则会引发ValueError
is raised.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]
andheapq.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 bekey可以是None
.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如果给定default,则在迭代器耗尽时返回,否则将引发StopIteration
is raised.StopIteration
。
-
class
object
¶ 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.此函数不接受任何参数。
-
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如果x不是Pythonint
object, it has to define an__index__()
method that returns an integer.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.OSError
。See 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(如果给定了文件描述符,则在关闭返回的I/O对象时关闭该描述符,除非closefd设置为False
.)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:在文本模式下,如果未指定encoding,则使用的编码取决于平台:将调用locale.getpreferredencoding(False)
is called to get the current locale 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以二进制模式打开的文件(包括mode参数中的'b'
in the mode argument) return contents asbytes
objects without any decoding.'b'
)以字节对象的形式返回内容,而不进行任何解码。In text mode (the default, or when在文本模式下(默认情况下,或当mode参数中包含't'
is included in the mode argument), the contents of the file are returned asstr
, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.'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请注意,这种方式指定缓冲区大小适用于二进制缓冲I/O,但TextIOWrapper
(i.e., files opened withmode='r+'
) would have another buffering.TextIOWrapper
(即,以mode='r+'
打开的文件)将有另一个缓冲。To disable buffering in要在TextIOWrapper
, consider using thewrite_through
flag forio.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()
returnsTrue
) 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编码不支持的字符将替换为相应的XML字符引用&#nnn;
.&#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从流中读取输入时,如果newline为None
, universal newlines mode is enabled.None
,则启用通用换行符模式。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将输出写入流时,如果newline为None
, any'\n'
characters written are translated to the system default line separator,os.linesep
.None
,则写入的任何'\n'
字符都会转换为系统默认的行分隔符os.linesep
。If newline is如果newline为''
or'\n'
, no translation takes place.''
或'\n'
,则不会进行转换。If newline is any of the other legal values, any如果newline是任何其他合法值,则写入的任何'\n'
characters written are translated to the given string.'\n'
字符都将转换为给定字符串。
If closefd is如果closefd为False
and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed.False
,并且提供了文件描述符而不是文件名,则在关闭文件时,基础文件描述符将保持打开状态。If a filename is given closefd must be如果给定文件名,closefd必须为True
(the default); otherwise, an error will be raised.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).然后通过使用(file,flags)调用opener来获取文件对象的底层文件描述符。openermust return an open file descriptor (passing必须返回一个打开的文件描述符(将os.open
as opener results in functionality similar to passingNone
).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 descriptorThe type of file object returned by theopen()
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 ofio.TextIOBase
(specificallyio.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 anio.BufferedWriter
, and in read/write mode, it returns anio.BufferedRandom
.io.BufferedReader
;在写二进制和附加二进制模式下,它返回一个io.BufferedWriter
,在读/写模式下,它返回一个io.BufferedRandom
。When 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
(whereopen()
is declared),os
,os.path
,tempfile
, andshutil
.fileinput
、io
(其中声明了open()
)、os
、os.path
、tempfile
和shutil
。Raises an auditing event引发一个审核事件,该事件使用参数open
with argumentsfile
,mode
,flags
.file
、mode
和flags
打开。Themode
andflags
arguments may have been modified or inferred from the original call.mode
和flags
参数可能已根据原始调用进行了修改或推断。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版中更改:Support added to accept objects implementing添加了支持以接受实现os.PathLike
.os.PathLike
的对象。On Windows, opening a console buffer may return a subclass of在Windows上,打开控制台缓冲区可能会返回io.RawIOBase
other thanio.FileIO
.io.RawIOBase
的子类,而不是io.FileIO
。
-
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 integer97
andord('€')
(Euro sign) returns8364
.ord('a')
返回整数97
,ord('€')
(欧元符号)返回8364
。This 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返回将base幂乘到exp;如果存在pow(base, exp) % mod
).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)
returns100
, butpow(10, -2)
returns0.01
.pow(10, 2)
返回100
,但pow(10, -2)
返回0.01
。For a negative base of type对于int
orfloat
and a non-integral exponent, a complex result is delivered.int
或float
类型的负基和非整数指数,将给出一个复杂的结果。For example,例如,pow(-9, 0.5)
returns a value close to3j
.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
操作数base和exp,如果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_base是base模mod的反比。Here’s an example of computing an inverse for下面是一个计算38
modulo97
:38
模97
的逆的例子:>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
TrueChanged in version 3.8:在3.8版中更改:For对于int
operands, the three-argument form ofpow
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分隔,后跟end。sep, end, file, and flush, if present, must be given as keyword arguments.sep、end、file和flush(如果存在)必须作为关键字参数提供。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分隔,后跟end。Both sep and end must be strings; they can also besep和end都必须是字符串;它们也可以是None
, which means to use the default values.None
,这意味着使用默认值。If no objects are given,如果没有objects,print()
will just write end.print()
将只写end。The file argument must be an object with afile参数必须是具有write(string)
method; if it is not present orNone
,sys.stdout
will be used.write(string)
方法的对象;如果不存在或None
,将使用sys.stdout
。Since 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关键字参数。
-
class
property
(fget=None, fset=None, fdel=None, doc=None)¶ Return a property attribute.返回一个属性。fget
is a function for getting an attribute value.是一个获取属性值的函数。fsetis a function for setting an attribute value.是用于设置属性值的函数。fdelis 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是C的实例,c.x
will invoke the getter,c.x = value
will invoke the setter, anddel c.x
the deleter.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._voltageThe@property
decorator turns thevoltage()
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
, anddeleter
methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.getter
、setter
和deleter
方法,这些方法可用作装饰器,用于创建属性的副本,并将相应的访问器函数设置为装饰函数。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._xThis 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
, andfdel
corresponding to the constructor arguments.fget
、fset
和fdel
。Changed in version 3.5:在3.5版中更改:The docstrings of property objects are now writeable.属性对象的docstring现在是可写的。
-
class
range
(stop) -
class
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.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.返回一个反向迭代器。seqmust be an object which has a必须是具有__reversed__()
method or supports the sequence protocol (the__len__()
method and the__getitem__()
method with integer arguments starting at0
).__reversed__()
方法或支持序列协议的对象(具有从0开始的整数参数的__len__()
方法和__getitem__()
方法)。
-
round
(number[, ndigits])¶ Return number rounded to ndigits precision after the decimal point.返回小数点后四舍五入到ndigits精度的number。If ndigits is omitted or is如果ndigits被省略或为None
, it returns the nearest integer to its input.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, bothround(0.5)
andround(-0.5)
are0
, andround(1.5)
is2
).round()
的内置类型,将值四舍五入到最接近幂减去ndigit的10倍;如果两个倍数相等,则舍入是朝偶数方向进行的(例如,round(0.5)
和round(-0.5)
均为0
,round(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如果省略ndigits或ndigits为None
.None
,则返回值为整数。Otherwise, the return value has the same type as number.否则,返回值的类型与number相同。For a general Python object对于一般的Python对象number
,round
delegates tonumber.__round__
.number
,round
委托为number.__round__
。Note
The behavior offloat的round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.68
.round()
行为可能令人惊讶:例如,round(2.675, 2)
给出的是2.67
,而不是预期的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 Floating Point Arithmetic: Issues and Limitations for more information.有关更多信息,请参阅浮点算术:问题和限制。
-
class
set
([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
, anddict
classes, as well as thecollections
module.frozenset
、list
、tuple
和dict
类,以及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 tox.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()
对其进行设置。
-
class
slice
(stop)¶ -
class
slice
(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 tostart和step参数默认为None
.None
。Slice objects have read-only data attributes切片对象具有只读数据属性start
,stop
, andstep
which merely return the argument values (or their default).start
、stop
和step
,这些属性仅返回参数值(或其默认值)。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]
ora[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指定一个参数的函数,用于从iterable中的每个元素中提取比较键(例如key=str.lower
).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 asC().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__
属性,现在可以作为常规函数调用。
-
class
str
(object='') -
class
str
(object=b'', encoding='utf-8', errors='strict') Return a返回object的str
version of object.str
版本。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.从左到右对start和iterable的项求和,并返回总数。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参数指定为关键字参数。
-
class
super
([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例如,如果object-or-type的__mro__
of object-or-type isD -> B -> C -> A -> object
and the value of type isB
, thensuper()
searchesC -> A -> object
.__mro__
是D -> B -> C -> A -> object
,并且type的值是B
,则super()
搜索C -> A -> object
。Theobject-or-type的__mro__
attribute of the object-or-type lists the method resolution search order used by bothgetattr()
andsuper()
.__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)
必须为true
。If 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 assuper().__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 assuper()[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()
指南。
-
class
tuple
([iterable]) Rather than being a function,tuple
is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.tuple
不是一个函数,而是一个不可变的序列类型,如元组和序列类型-列表、元素和范围中所述。
-
class
type
(object)¶ -
class
type
(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 thename字符串是类名,并成为__name__
attribute.__name__
属性。The bases tuple contains the base classes and becomes thebases元组包含基类,并成为__bases__
attribute; if empty,object
, the ultimate base of all classes, is added.__bases__
属性;如果为空,则添加所有类的最终基object
。The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming thedict字典包含类主体的属性和方法定义;在成为__dict__
attribute.__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.另请参见自定义类创建。
-
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 atypes.MappingProxyType
to prevent direct dictionary updates).__dict__
属性;但是,其他对象可能对其__dict__
属性有写限制(例如,类使用types.MappingProxyType
来防止直接更新字典)。Without an argument,没有参数,vars()
acts likelocals()
.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 afor
loop or by wrapping in alist
.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 1Without 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,边缘情形:使用单个iterable参数,zip()
returns an iterator of 1-tuples.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这会将same迭代器重复n
times so that each output tuple has the result ofn
calls to the iterator.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这是日常Python编程中不需要的高级函数,与importlib.import_module()
.importlib.import_module()
不同。This function is invoked by the此函数由import
statement.import
语句调用。It can be replaced (by importing the为了改变builtins
module and assigning tobuiltins.__import__
) in order to change semantics of theimport
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 ofimportlib.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标准实现根本不使用其locals参数,只使用其globals来确定import
statement.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 callinglevel的正值表示相对于调用__import__()
(see PEP 328 for the details).__import__()
的模块的目录要搜索的父目录数(有关详细信息,请参阅PEP 328)。When the name variable is of the form当name变量的形式为package.module
, normally, the top-level package (the name up till the first dot) is returned, not the module named by 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 statementimport 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 theimport
statement.__import__()
如何在此处返回顶级模块,因为这是通过import
语句绑定到名称的对象。On the other hand, the statement另一方面,语句from spam.ham import eggs, sausage as saus
results infrom spam.ham import eggs, sausage as saus
导致_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausageHere, 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 variablePYTHONCASEOK
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风格的换行符。