内置函数

Python 解释器有很多始终可用的内置函数和类型。在此按字母顺序列表它们。

内置函数

abs ( x )

返回数字的绝对值。自变量可以是整数、浮点数或对象有实现 __abs__() 。若自变量是复数,返回其幅度。

aiter ( async_iterable )

返回 异步迭代器 对于 异步可迭代 。相当于调用 x.__aiter__() .

注意:不像 iter() , aiter() 没有 2 自变量变体。

Added in version 3.10.

all ( iterable )

返回 True 若所有元素在 iterable 为 true (或者若可迭代为空)。相当于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
						
awaitable anext ( async_iterator )
awaitable anext ( async_iterator , default )

当等待时,返回下一项从给定 异步迭代器 ,或 default 若有给定且迭代器耗尽。

这是 async 变体的 next() 内置,且行为类似。

这调用 __anext__() 方法为 async_iterator ,返回 awaitable 。等待这返回迭代器的下一值。若 default 有给定,返回它若迭代器耗尽,否则 StopAsyncIteration 被引发。

Added in version 3.10.

any ( iterable )

返回 True 若任何元素在 iterable 为 True。若可迭代为空,返回 False 。相当于:

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

As repr() ,返回包含对象可打印表示的字符串,但转义字符串中的非 ASCII 字符的返回通过 repr() 使用 \x , \u ,或 \U 转义。这生成的字符串类似返回通过 repr() 在 Python 2。

bin ( x )

将整数转换成具有 0b 前缀的二进制字符串。结果是有效 Python 表达式。若 x 不是 Python int 对象,它必须定义 __index__() 方法为返回整数。某些范例:

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

若期望 (或不期望) 0b 前缀,可以使用以下任一方式。

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

另请参阅 format() 了解更多信息。

class bool ( object = False , / )

返回布尔值,即: True or False . The argument is converted using the standard 真值测试过程 . If the argument is false or omitted, this returns False ;否则,它返回 True bool 类是子类化的 int (见 数值类型 — 整数、浮点数、复数 )。它无法进一步子类化。它的唯一实例是 False and True (见 Boolean Type - bool ).

3.7 版改变: The parameter is now positional-only.

breakpoint ( * args , ** kws )

此函数将您丢进调用站点调试器。具体来说,它调用 sys.breakpointhook() ,传递 args and kws 直接通过。默认情况下, sys.breakpointhook() 调用 pdb.set_trace() 期待没有自变量。在此情况下,它纯粹是方便函数,所以不必明确导入 pdb 或如进入调试器般多代码的类型。不管怎样, sys.breakpointhook() 可以被设为其它函数且 breakpoint() 会自动调用它,使您能够进入所选调试器。若 sys.breakpointhook() 不可访问,此函数会引发 RuntimeError .

By default, the behavior of breakpoint() can be changed with the PYTHONBREAKPOINT 环境变量。见 sys.breakpointhook() for usage details.

Note that this is not guaranteed if sys.breakpointhook() has been replaced.

引发 审计事件 builtins.breakpoint 采用自变量 breakpointhook .

Added in version 3.7.

class bytearray ( source = b'' )
class bytearray ( source , encoding )
class bytearray ( source , encoding , errors )

返回新的字节数组。 bytearray 类是在 0 <= x < 256 范围的可变整数序列。它拥有可变序列的大多数通常方法,描述在 可变序列类型 ,及大多数方法如 bytes 类型拥有的,见 bytes 和 bytearray 操作 .

可选 source 参数可以用于按几种不同方式初始化数组:

  • 若它是 string ,还必须给出 encoding (和可选, errors ) 参数; bytearray() 则将字符串转换为字节使用 str.encode() .

  • 若它是 integer ,数组将拥有该大小并将采用 Null 字节进行初始化。

  • 若它是对象且符合 缓冲接口 ,将使用对象的只读缓冲初始化字节数组。

  • 若它是 iterable ,它必须是整数的可迭代在范围 0 <= x < 256 ,用作数组的初始内容。

没有自变量,创建 0 大小的数组。

另请参阅 二进制序列类型 — 字节、字节数组、内存视图 and bytearray 对象 .

class bytes ( source = b'' )
class bytes ( source , encoding )
class bytes ( source , encoding , errors )

返回是不可变整数序列的新 bytes 对象,在范围 0 <= x < 256 . bytes 是不可变版本的 bytearray – 它拥有相同非变异方法、相同索引及切片行为。

故此,构造函数自变量的解释如同 bytearray() .

也可以采用文字创建字节对象,见 字符串和 bytes 文字 .

另请参阅 二进制序列类型 — 字节、字节数组、内存视图 , bytes 对象 ,和 bytes 和 bytearray 操作 .

callable ( object )

返回 True object 自变量看起来可调用, False 若不。若这返回 True ,调用仍可能失败,但若为 False ,调用 object 从不会成功。注意,类是可调用的 (调用类返回新实例);实例是可调用的若它们的类拥有 __call__() 方法。

Added in version 3.2: 此函数首先在 Python 3.0 被移除,然后在 Python 3.2 被带回。

chr ( i )

返回表示字符的字符串,其 Unicode 代码点是整数 i 。例如, chr(97) 返回字符串 'a' ,而 chr(8364) 返回字符串 '€' 。这是逆 ord() .

有效自变量范围是从 0 到 1,114,111 (以 16 为基的 0x10FFFF)。 ValueError 会被引发若 i 在该范围之外。

@ classmethod

把方法变换成类方法。

类方法接收类作为第一隐式自变量,就像实例方法接收实例。要声明类方法,请用此习语:

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

The @classmethod 形式是函数 装饰器 – 见 函数定义 了解细节。

类方法可以被调用在类 (譬如 C.f() ) 或在实例 (譬如 C().f() )。实例被忽略,除它的类外。若派生类调用类方法,则派生类对象作为隐式第一自变量被传递。

类方法不同于 C++ 或 Java 静态方法。若想要这些,见 staticmethod() 在此节中。有关类方法的更多信息,见 标准类型层次结构 .

3.9 版改变: 类方法现在可以包裹其它 descriptors 譬如 property() .

3.10 版改变: 类方法现在继承方法属性 ( __module__ , __name__ , __qualname__ , __doc__ and __annotations__ ) 且拥有新的 __wrapped__ 属性。

3.11 版改变: 类方法可以不再包裹其它 descriptors 譬如 property() .

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

编译 source 成代码或 AST (抽象句法树) 对象。可以执行代码对象通过 exec() or eval() . source 可以是正常字符串、字节字符串或 AST 对象。参考 ast 模块文档编制,了解如何操控 AST 对象的有关信息。

The filename 自变量是应该给出从中读取代码的文件;传递一些可识别值,若不从文件读取 ( '<string>' 很常用)。

The mode 自变量指定必须编译哪种代码;它可以是 'exec' if source 由一系列语句组成, 'eval' 若它由单个表达式组成,或 'single' 若它由单个交互式语句组成 (后一种情况,评估为某物的表达式语句而不是 None 会被打印)。

可选自变量 flags and dont_inherit 控制哪个 编译器选项 应该被激活和哪个 未来特征 应该被允许。若两者都不存在 (或两者为 0),则采用影响代码的相同标志编译代码,调用 compile() 。若 flags 自变量有给定且 dont_inherit 不给定 (或为 0) 那么编译器选项和未来语句的指定通过 flags 自变量的使用,除无论如何会使用的哪些外。若 dont_inherit 是非 0 整数那么 flags 自变量是围绕代码被忽略的标志 (未来特征和编译器选项)。

编译器选项和未来语句,由可以按位 OR (或) 到一起指定多个选项的位指定。指定给定未来特征要求的位字段可以找到作为 compiler_flag 属性在 _Feature 实例在 __future__ 模块。 编译器标志 可以找到在 ast 模块,采用 PyCF_ 前缀。

自变量 optimize 指定编译器的优化级别;默认值 -1 选择解释器的优化级别作为给出通过 -O 选项。明确级别为 0 (不优化; __debug__ 为 True), 1 (断言被移除, __debug__ 为 False) 或 2 (还移除 docstring 文档字符串)。

此函数引发 SyntaxError 若编译源无效,和 ValueError 若 source 包含 null 字节。

若想要将 Python 代码剖析成 AST 表示,见 ast.parse() .

引发 审计事件 compile 采用自变量 source and filename 。此事件也可能由隐式编译引发。

注意

当编译具有多行代码的字符串按 'single' or 'eval' 模式,输入必须以至少一换行符结尾。这促进检测不完整完整和完整语句在 code 模块。

警告

由于 Python 的 AST (抽象句法树) 编译器的堆栈深度局限性,当编译到 AST 对象时,采用足够大的 (复杂) 字符串 Python 解释器可能崩溃。

3.2 版改变: 允许使用 Windows 和 Mac 换行符。此外,输入在 'exec' 模式必须不再以换行符结束。添加 optimize 参数。

3.5 版改变: 先前, TypeError 被引发当遭遇 null 字节在 source .

Added in version 3.8: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT 现在可以传入标志以启用支持顶层 await , async for ,和 async with .

class complex ( number = 0 , / )
class complex ( string , / )
class complex ( real = 0 , imag = 0 )

Convert a single string or number to a complex number, or create a complex number from real and imaginary parts.

范例:

>>> complex('+1.23')
(1.23+0j)
>>> complex('-4.5j')
-4.5j
>>> complex('-1.23+4.5j')
(-1.23+4.5j)
>>> complex('\t( -1.23+4.5J )\n')
(-1.23+4.5j)
>>> complex('-Infinity+NaNj')
(-inf+nanj)
>>> complex(1.23)
(1.23+0j)
>>> complex(imag=-4.5)
-4.5j
>>> complex(-1.23, 4.5)
(-1.23+4.5j)
								

If the argument is a string, it must contain either a real part (in the same format as for float() ) or an imaginary part (in the same format but with a 'j' or 'J' suffix), or both real and imaginary parts (the sign of the imaginary part is mandatory in this case). The string can optionally be surrounded by whitespaces and the round parentheses '(' and ')' , which are ignored. The string must not contain whitespace between '+' , '-' 'j' or 'J' suffix, and the decimal number. For example, complex('1+2j') 很好,但 complex('1 + 2j') 引发 ValueError . More precisely, the input must conform to the complexvalue production rule in the following grammar, after parentheses and leading and trailing whitespace characters are removed:

complexvalue ::=  floatvalue |
                  floatvalue ("j" | "J") |
                  floatvalue sign absfloatvalue ("j" | "J")
								

If the argument is a number, the constructor serves as a numeric conversion like int and float . For a general Python object x , complex(x) 委托 x.__complex__() 。若 __complex__() is not defined then it falls back to __float__() 。若 __float__() is not defined then it falls back to __index__() .

If two arguments are provided or keyword arguments are used, each argument may be any numeric type (including complex). If both arguments are real numbers, return a complex number with the real component real and the imaginary component imag . If both arguments are complex numbers, return a complex number with the real component real.real-imag.imag and the imaginary component real.imag+imag.real . If one of arguments is a real number, only its real component is used in the above expressions.

If all arguments are omitted, returns 0j .

复杂类型的描述在 数值类型 — 整数、浮点数、复数 .

3.6 版改变: 允许按代码文字下划线分组数字。

3.8 版改变: 回退到 __index__() if __complex__() and __float__() 未定义。

delattr ( object , name )

这相对于 setattr() 。自变量是对象和字符串。字符串必须是对象属性名称之一。函数将删除命名属性,若提供的对象允许。例如, delattr(x, 'foobar') 相当于 del x.foobar . name 不需要是 Python 标识符 (见 setattr() ).

class dict ( ** kwarg )
class dict ( 映射 , ** kwarg )
class dict ( iterable , ** kwarg )

创建新字典。 dict 对象是字典类。见 dict and 映射类型 — dict 有关此类的文档编制。

对于其它容器,见内置 list , set ,和 tuple 类,及 collections 模块。

dir ( )
dir ( object )

不带自变量,返回当前本地作用域中的名称列表。带自变量,试图返回该对象的有效属性列表。

若对象拥有方法名 __dir__() ,会调用此方法,且必须返回属性列表。这允许对象实现自定义 __getattr__() or __getattribute__() 函数以定制方式 dir() 报告它们的属性。

若对象不提供 __dir__() , the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete and may be inaccurate when the object has a custom __getattr__() .

默认 dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • 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.

结果列表按字母顺序排序。例如:

>>> 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']
									

注意

因为 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. 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) . For floating point numbers the result is (q, a % b) ,其中 q 通常是 math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a ,若 a % b is non-zero it has the same sign as b ,和 0 <= abs(a % b) < abs(b) .

enumerate ( iterable , start = 0 )

返回枚举对象。 iterable 必须是序列, iterator ,或支持迭代的某些其它对象。 __next__() 方法对于迭代器返回通过 enumerate() 返回元组包含计数 (从 start 其默认为 0) 和值获取自遍历 iterable .

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

等效于:

def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
										
eval ( 表达式 , globals = None , locals = None )
参数 :
  • 表达式 ( str | code object ) – A Python expression.

  • globals ( dict | None ) – The global namespace (default: None ).

  • locals ( 映射 | None ) – The local namespace (default: None ).

返回 :

The result of the evaluated expression.

引发 :

Syntax errors are reported as exceptions.

The 表达式 argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__ , a reference to the dictionary of the built-in module builtins is inserted under that key before 表达式 is parsed. 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() 。若 locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

范例:

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

This function can also be used to execute arbitrary code objects (such as those created by compile() ). In this case, pass a code object instead of a string. If the code object has been compiled with 'exec' 作为 mode 自变量, eval() 的返回值将是 None .

提示:语句动态执行的支持通过 exec() 函数。 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() .

若给定源是字符串,那么会剥离前导和结尾的空格和 Tab。

ast.literal_eval() 了解可以安全评估仅包含文字的字符串表达式的函数。

引发 审计事件 exec 采用代码对象作为自变量。还可能引发代码编译事件。

exec ( object , globals = None , locals = None , / , * , closure = None )

此函数支持 Python 代码的动态执行。 object 必须是字符串 (或代码对象)。若它是字符串,则字符串会被剖析成一套 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 文件输入 in the Reference Manual). Be aware that the nonlocal , yield ,和 return 语句不可以用于函数定义外,即使在代码上下文内被传递给 exec() 函数。返回值为 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. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary.

注意

Most users should just pass a globals argument and never locals . If exec gets two separate objects as globals and locals , the code will be executed as if it were embedded in a class definition.

globals 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. 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() .

The closure argument specifies a closure–a tuple of cellvars. It’s only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.

引发 审计事件 exec 采用代码对象作为自变量。还可能引发代码编译事件。

注意

内置函数 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() .

注意

默认 locals 作用的描述按函数 locals() 下文:修改默认 locals 字典不应尝试。传递明确 locals 字典若需要查看代码效果在 locals 后于函数 exec() 返回。

3.11 版改变: 添加 closure 参数。

filter ( function , iterable )

构造迭代器的那些元素来自 iterable 其中 function 为 True。 iterable 可以是序列、支持迭代的容器或迭代器。若 function is None , the identity function is assumed, that is, all elements of iterable that are false are removed.

注意, filter(function, iterable) 相当于生成器表达式 (item for item in iterable if function(item)) 若函数不为 None and (item for item in iterable if item) 若函数为 None .

itertools.filterfalse() for the complementary function that returns elements of iterable 其中 function 为 False。

class float ( number = 0.0 , / )
class float ( string , / )

Return a floating point number constructed from a number or a string.

范例:

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

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. More precisely, the input must conform to the floatvalue production rule in the following grammar, after leading and trailing whitespace characters are removed:

sign          ::=  "+" | "-"
infinity      ::=  "Infinity" | "inf"
nan           ::=  "nan"
digit         ::=  <a Unicode decimal digit, i.e. characters in Unicode general category Nd>
digitpart     ::=  digit (["_"] digit)*
number        ::=  [digitpart] "." digitpart | digitpart ["."]
exponent      ::=  ("e" | "E") [sign] digitpart
floatnumber   ::=  number [exponent]
absfloatvalue ::=  floatnumber | infinity | nan
floatvalue    ::=  [sign] absfloatvalue
											

Case is not significant, so, for example, “inf”, “Inf”, “INFINITY”, and “iNfINity” are all acceptable spellings for positive 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. If the argument is outside the range of a Python float, an OverflowError 会被引发。

对于一般 Python 对象 x , float(x) 委托 x.__float__() 。若 __float__() is not defined then it falls back to __index__() .

若不给出自变量, 0.0 被返回。

浮点类型的描述在 数值类型 — 整数、浮点数、复数 .

3.6 版改变: 允许按代码文字下划线分组数字。

3.7 版改变: The parameter is now positional-only.

3.8 版改变: 回退到 __index__() if __float__() 未定义。

format ( value , format_spec = '' )

转换 value 按 "格式化" 表示,如控制通过 format_spec 。解释 format_spec 将从属其类型对于 value argument; however, there is a standard formatting syntax that is used by most built-in types: 格式规范迷你语言 .

默认 format_spec 是空字符串,通常给出相同的效果如调用 str(value) .

调用 format(value, format_spec) 会被翻译成 type(value).__format__(value, format_spec) 以绕过实例字典,当搜索值的 __format__() 方法。 TypeError 异常被引发若方法搜索到达 object format_spec 非空,或者若 format_spec 或返回值不是字符串。

3.4 版改变: object().__format__(format_spec) 引发 TypeError if format_spec 不是空字符串。

class frozenset ( iterable = set() )

返回新的 frozenset 对象,可选采用元素取自 iterable . frozenset 是内置类。见 frozenset and 集类型 — set、frozenset 有关此类的文档编制。

对于其它容器,见内置 set , list , tuple ,和 dict 类,及 collections 模块。

getattr ( object , name )
getattr ( object , name , default )

返回命名属性的值为 object . name 必须是字符串。若字符串是对象属性名称之一,结果就是该属性的值。例如, getattr(x, 'foobar') 相当于 x.foobar 。若命名属性不存在, default 被返回若有提供,否则 AttributeError 被引发。 name 不需要是 Python 标识符 (见 setattr() ).

注意

由于 私有名称重整 发生在编译时,必须手动重整私有属性 (带有 2 前导下划线的属性) 名称,为检索它采用 getattr() .

globals ( )

返回实现当前模块名称空间的字典。对于函数内代码,这是在定义函数时设置的,且不管在哪里调用函数仍然一样。

hasattr ( object , name )

自变量是对象和字符串。结果为 True 若字符串是对象某一属性的名称, False 若不是。(这被实现通过调用 getattr(object, name) 和看它是否引发 AttributeError 或不。)

hash ( object )

返回对象的哈希值 (若有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数值拥有相同哈希值 (即使它们是不同类型,如 1 和 1.0 的情况)。

注意

对于对象具有自定义 __hash__() 方法,注意 hash() truncates the return value based on the bit width of the host machine.

help ( )
help ( request )

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. For more info, see the FAQ entry on positional-only parameters .

此函数已添加到内置名称空间通过 site 模块。

3.4 版改变: Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.

hex ( x )

把整数转换成采用 0x 作前缀的小写十六进制字符串。若 x 不是 Python int 对象,它必须定义 __index__() 方法为返回整数。某些范例:

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

另请参阅 format() 了解更多信息。

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

注意

要获得浮点数的十六进制字符串表示,使用 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() 值。

CPython 实现细节: 这是对象在内存中的地址。

引发 审计事件 builtins.id 采用自变量 id .

input ( )
input ( prompt )

prompt 自变量存在,将不带结尾换行符将它写入标准输出。然后,函数从输入读取一行,将其转换为字符串 (去掉末尾换行符),并返回该字符串。 EOFError 被引发。范例:

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

readline 模块被加载,则 input() 将使用它来提供详尽行编辑和历史特征。

引发 审计事件 builtins.input 采用自变量 prompt 在读取输入前

引发 审计事件 builtins.input/result 采用结果在成功读取输入后。

class int ( number = 0 , / )
class int ( string , / , base = 10 )

Return an integer object constructed from a number or a string, or return 0 if no arguments are given.

范例:

>>> int(123.45)
123
>>> int('123')
123
>>> int('   -12_345\n')
-12345
>>> int('FACE', 16)
64206
>>> int('0xface', 0)
64206
>>> int('01110011', base=2)
115
													

If the argument defines __int__() , int(x) 返回 x.__int__() . If the argument defines __index__() ,它返回 x.__index__() . If the argument defines __trunc__() ,它返回 x.__trunc__() 。对于浮点数,这朝 0 截取。

If the argument is not a number or if base is given, then it must be a string, bytes ,或 bytearray instance representing an integer in radix base . Optionally, the string can be preceded by + or - (with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.

A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0–9 can be represented by any Unicode decimal digit. The values 10–35 can be represented by a to z (或 A to Z ). The default base is 10. The allowed bases are 0 and 2–36. Base-2, -8, and -16 strings can be optionally prefixed with 0b / 0B , 0o / 0O ,或 0x / 0X , as with integer literals in code. For base 0, the string is interpreted in a similar way to an integer literal in code , in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros: int('010', 0) is not legal, while int('010') and int('010', 8) are.

整数类型的描述在 数值类型 — 整数、浮点数、复数 .

3.4 版改变: base 不是实例化的 int base 对象拥有 base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ 而不是 base.__index__ .

3.6 版改变: 允许按代码文字下划线分组数字。

3.7 版改变: The first parameter is now positional-only.

3.8 版改变: 回退到 __index__() if __int__() 未定义。

3.11 版改变: 委托给 __trunc__() 被弃用。

3.11 版改变: int string inputs and string representations can be limited to help avoid denial of service attacks. A ValueError is raised when the limit is exceeded while converting a string to an int or when converting an int into a string would exceed the limit. See the 整数字符串转换长度局限性 文档编制。

isinstance ( object , classinfo )

返回 True object 自变量是实例对于 classinfo 自变量,或对于 (直接、间接或 virtual ) 其子类。若 object 不是给定类型的对象,函数始终返回 False 。若 classinfo is a tuple of type objects (or recursively, other such tuples) or a Union 类型 of multiple types, return True if object 是任何类型的实例。若 classinfo 不是类型 (或类型和这种元组的元组), TypeError 异常被引发。 TypeError may not be raised for an invalid type if an earlier check succeeds.

3.10 版改变: classinfo 可以是 Union 类型 .

issubclass ( class , classinfo )

返回 True if class 是 子类 (直接、间接或 virtual ) of classinfo 。类被认为是自身的子类。 classinfo may be a tuple of class objects (or recursively, other such tuples) or a Union 类型 , in which case return True if class is a subclass of any entry in classinfo . In any other case, a TypeError 异常被引发。

3.10 版改变: classinfo 可以是 Union 类型 .

iter ( object )
iter ( object , sentinel )

返回 iterator 对象。第一自变量的解释非常不同,从属存在的第二自变量。没有第二自变量, object 必须是集合对象支持 iterable 协议 ( __iter__() 方法),或它必须支持序列协议 ( __getitem__() 方法采用的整数自变量开始于 0 )。若它不支持这些协议, TypeError 被引发。若第 2 自变量 sentinel 有给定,那么 object 必须是可调用对象。在这种情况下创建的迭代器将调用 object 不采用自变量每次调用其 __next__() 方法;若返回值等于 sentinel , StopIteration 将被引发,否则会返回值。

另请参阅 迭代器类型 .

第 2 种形式的有用应用程序对于 iter() 是构建阻塞读取器。例如,从二进制数据库文件读取固定宽度的块,直到到达 EOF (文件末尾):

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 )

返回对象的长度 (项数)。自变量可以是序列 (譬如:字符串、字节、元组、列表或范围) 或集合 (譬如:字典、集或冻结集)。

CPython 实现细节: len 引发 OverflowError 当长度大于 sys.maxsize ,譬如 range(2 ** 100) .

class list
class list ( iterable )

除了是函数, list 实际是可变序列类型,如文档化在 列表 and 序列类型 — 列表、元组、范围 .

locals ( )

更新并返回表示当前本地符号表的字典。自由变量的返回是通过 locals() 当调用它是在函数块中,而不是在类块中时。注意,在模块级别, locals() and globals() 是同一字典。

注意

此词典的内容不应被修改;更改可能不影响由解释器使用的局部变量和自由变量的值。

map ( function , iterable , * iterables )

返回的迭代器应用 function 到每项为 iterable ,产生结果。若额外 iterables 自变量有传递, function 必须接受那么多个自变量并平行应用于所有可迭代项。采用多个可迭代,迭代器停止当最短可迭代耗尽时。对于函数输入已经排列成自变量元组的情况,见 itertools.starmap() .

max ( iterable , * , key = None )
max ( iterable , * , default , key = None )
max ( arg1 , arg2 , * args , key = None )

返回可迭代中的最大项 (或 2 个或多个自变量中的最大项)。

若提供的是 1 位置自变量,它应该是 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() default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and 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) .

3.4 版改变: 添加 default 仅关键词参数。

3.8 版改变: The key 可以是 None .

class memoryview ( object )

返回从给定自变量创建的内存视图对象。见 内存视图 了解更多信息。

min ( iterable , * , key = None )
min ( iterable , * , default , key = None )
min ( arg1 , arg2 , * args , key = None )

返回可迭代中的最小项 (或 2 个或多个自变量中的最小项)。

若提供的是 1 位置自变量,它应该是 iterable . The smallest item in the iterable is returned. 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() default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and 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) .

3.4 版改变: 添加 default 仅关键词参数。

3.8 版改变: The key 可以是 None .

next ( iterator )
next ( iterator , default )

检索下一项从 iterator 通过调用其 __next__() 方法。若 default 有给定,返回它若迭代器耗尽,否则 StopIteration 被引发。

class object

返回新的无特征对象。 object 是所有类的基。它拥有所有 Python 类实例公共方法。此函数不接受任何自变量。

注意

object does not 拥有 __dict__ ,所以不可以将任意属性赋值给其实例对于 object 类。

oct ( x )

把整数转换成采用 0o 作前缀的八进制字符串。结果是有效 Python 表达式。若 x 不是 Python int 对象,它必须定义 __index__() 方法返回整数。例如:

>>> 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.

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

另请参阅 format() 了解更多信息。

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

打开 file 并返回相应 文件对象 。若文件无法打开, OSError 被引发。见 读写文件 了解如何使用此函数的更多范例。

file 像路径对象 给出要打开的文件路径名 (绝对或相对于当前工作目录) 或要包裹文件的整数文件描述符 (若给定文件描述符,会关闭它当关闭返回的 I/O 对象时,除非 closefd 被设为 False )。

mode 是指定文件打开模式的可选字符串。默认为 'r' 意味着以文本模式打开以供读取。其它常见值 'w' 以供写入 (截取文件若已存在), 'x' 以供独占创建,和 'a' 以供追加 (在 some Unix 系统,意味着 all 写入将追加到 EOF 文件末尾,不管当前寻址位置)。在文本模式,若 encoding 未指定,使用编码从属平台: locale.getencoding() 被调用以获取当前区域设置编码 (为读取和写入原生字节,使用二进制模式并留下 encoding 不指定)。可用模式包含:

字符

含义

'r'

打开以供读取 (默认)

'w'

打开以供写入,先截取文件

'x'

打开以供独占创建,会失败若文件已存在

'a'

打开以供写入,追加到 EOF (文件末尾) 若存在

'b'

二进制模式

't'

文本模式 (默认)

'+'

打开以供更新 (读取和写入)

默认模式为 'r' (打开以供读取文本,同义词 'rt' )。模式 'w+' and 'w+b' 打开并截取文件。模式 'r+' and 'r+b' 打开文件不截取。

如提及在 概述 ,Python 区分二进制和文本 I/O。以二进制模式打开文件 (包括 'b' mode 自变量) 返回内容按 bytes 对象没有任何解码。以文本模式 (默认,或当 't' 包括在 mode 自变量), 返回文件内容是按 str ,必须先解码字节使用从属平台编码或使用指定 encoding 若给定。

注意

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 when writing in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but TextIOWrapper (即:文件打开采用 mode='r+' ) 将拥有另一种缓冲。要禁用缓冲在 TextIOWrapper ,考虑使用 write_through 标志为 io.TextIOWrapper.reconfigure() 。当没有 buffering 自变量的给定,默认缓冲策略工作如下:

  • 二进制文件按固定大小分块方式缓冲;使用缓冲大小的选取是试探性试着确定底层设备的 "块大小" 并回退到 io.DEFAULT_BUFFER_SIZE 。在很多系统,缓冲通常为 4096 或 8192 字节长。

  • "交互" 文本文件 (文件 isatty() 返回 True ) 使用行缓冲。其它文本文件使用上述二进制文件策略。

encoding 是用于解码 (或编码) 文件的编码名称。这只应用于文本模式。默认编码从属平台 (不管 locale.getencoding() 返回),但任何 文本编码 由 Python 支持的都可以使用。见 codecs 模块,了解支持的编码列表。

errors 是指定如何处理编码和解码错误的可选字符串 — 这不可以用于二进制模式。有各种可用标准错误处理程序 (列出于 错误处理程序 ),尽管任何错误处理名称已注册采用 codecs.register_error() 也是有效的。标准名称包括:

  • 'strict' 会引发 ValueError 异常若存在编码错误。默认值 None 有相同效果。

  • 'ignore' 忽略错误。注意,忽略编码错误会导致数据丢失。

  • 'replace' 导致置换标记 (譬如 '?' ) 被插入在畸形数据处。

  • 'surrogateescape' 会把任何不正确 bytes 表示成 U+DC80 到 U+DCFF 范围的低代理代码单元。然后,将这些代理代码单元转换成相同 bytes 当 surrogateescape 错误处理程序被使用,在写入数据时。这对处理未知编码的文件,很有用。

  • 'xmlcharrefreplace' 才支持当写入文件时。编码不支持的字符会被替换成适当 XML 字符引用 &#nnn; .

  • 'backslashreplace' 以 Python 反斜杠转义序列替换畸形数据。

  • 'namereplace' (也在写入时才支持) 替换不支持字符采用 \N{...} 转义序列。

newline 确定如何剖析来自流的换行符。它可以是 None , '' , '\n' , '\r' ,和 '\r\n' 。其工作如下:

  • 当从流读取输入时,若 newline is None ,启用通用换行符模式。输入中的行可以结束于 '\n' , '\r' ,或 '\r\n' ,且这些会被翻译成 '\n' 在返回给调用者之前。若为 '' ,启用通用换行符模式,但行结束会未经翻译返回给调用者。若它拥有任何其它合法值,输入行仅以给定字符串结尾,且行结束会未经翻译返回给调用者。

  • 当写入输出到流时,若 newline is None ,任何 '\n' 写入字符被翻译成系统默认行分隔符, os.linesep 。若 newline is '' or '\n' ,不发生翻译。若 newline 是任何其它合法值,任何 '\n' 写入字符被翻译成给定字符串。

closefd is False 且给定文件描述符而不是文件名,底层文件描述符将保持打开,当关闭文件时。若给定文件名 closefd 必须为 True (默认);否则,会引发错误。

自定义开启器可以用于传递可调用如 opener 。然后,获得文件对象底层文件描述符通过调用 opener 采用 ( file , flags ). opener 必须返回打开文件描述符 (传递 os.open as opener 导致功能类似于传递 None ).

新近创建的文件 不可继承 .

以下范例使用 dir_fd 参数为 os.open() 函数以打开相对给定目录的文件:

>>> 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
															

类型对于 文件对象 返回通过 open() 函数从属模式。当 open() 被用来打开文件按文本模式 ( 'w' , 'r' , 'wt' , 'rt' ,等),它返回子类化的 io.TextIOBase (专门 io.TextIOWrapper )。当采用缓冲按二进制模式用来打开文件,返回类是子类化的 io.BufferedIOBase 。准确类各不相同:在二进制读取模式下,它返回 io.BufferedReader ;在二进制写入和二进制追加模式下,它返回 io.BufferedWriter , 和在读取/写入模式下,它返回 io.BufferedRandom 。当缓冲被禁用时,原生流子类化的 io.RawIOBase , io.FileIO ,被返回。

另请参阅文件处理模块,譬如 fileinput , io (在哪里 open() 有声明), os , os.path , tempfile ,和 shutil .

引发 审计事件 open 采用自变量 file , mode , flags .

The mode and flags 自变量可能已被修改 (或推断自原始调用)。

3.3 版改变:

  • The opener 参数被添加。

  • The 'x' 模式被添加。

  • IOError 用于被引发,它现在是别名化的 OSError .

  • FileExistsError 现被引发若按独占创建模式打开的文件 ( 'x' ) 已存在。

3.4 版改变:

  • 文件现在不可继承。

3.5 版改变:

  • 若系统调用被中断且信号处理程序未引发异常,函数现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

  • The 'namereplace' 错误处理程序被添加。

3.6 版改变:

3.11 版改变: The 'U' 模式被移除。

ord ( c )

给定表示一 Unicode 字符的字符串,返回整数表示该字符的 Unicode 代码点。例如, ord('a') 返回整数 97 and ord('€') (欧元符号) 返回 8364 。这是逆 chr() .

pow ( base , exp , mod = None )

返回 base 到幂 exp ;若 mod 存在,返回 base 到幂 exp ,模 mod (计算更高效相比 pow(base, exp) % mod )。2 自变量形式 pow(base, exp) 相当于使用幂运算符: base**exp .

自变量必须拥有数字类型。采用混合操作数类型,会应用二进制算术运算符强制规则。对于 int 操作数,结果与操作数类型相同 (在强制后),除非第 2 自变量为负;在此情况下,所有自变量会被转换成浮点,并交付浮点结果。例如 pow(10, 2) 返回 100 ,但 pow(10, -2) 返回 0.01 。对于负值基类型 int or float 和非整型指数,交付复数结果。例如 pow(-9, 0.5) 返回接近值 3j .

For int 操作数 base and exp ,若 mod 存在, mod 还必须是整数类型,且 mod 必须非 0。若 mod 存在且 exp 为负, base 必须是相对素数对于 mod 。在此情况下, pow(inv_base, -exp, mod) 被返回,其中 inv_base 是逆 base mod .

这里的计算范例逆 38 97 :

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

3.8 版改变: For int 操作数,3 自变量形式的 pow 现在允许第 2 自变量为负,准许计算模逆。

3.8 版改变: 允许关键词自变量。以前,只支持位置自变量。

print ( * objects , sep = ' ' , end = '\n' , file = None , flush = False )

打印 对象 到文本流 file ,分隔通过 sep 且之后紧跟 end . sep , end , file ,和 flush ,若存在,必须以关键词自变量形式给出。

会将所有非关键自变量转换成字符串像 str() 所做的并写入流,分隔通过 sep 且之后紧跟 end 。两者 sep and end 必须为字符串;它们还可以为 None ,意味着使用默认值。若没有 对象 的给定, print() 将仅仅写入 end .

The file 自变量必须是对象具有 write(string) 方法;若它不存在或为 None , sys.stdout 会被使用。由于打印自变量会被转换成文本字符串, print() 不可以用于二进制模式文件对象。对于这些,使用 file.write(...) 代替。

Output buffering is usually determined by file . However, if flush is true, the stream is forcibly flushed.

3.3 版改变: 添加 flush 关键词自变量。

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

返回特性属性。

fget 是用于获取属性值的函数。 fset 是用于设置属性值的函数。 fdel 是用于删除属性值的函数。和 doc 为属性创建 docstring (文档字符串)。

典型用法是定义管理属性 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.")
															

c 是实例化的 C , c.x 将援引 getter, c.x = value will invoke the setter, and del c.x deleter。

若给定, doc 将是 property 属性的 docstring (文档字符串)。否则,特性将拷贝 fget 的文档字符串 (若存在)。这使之可能轻松创建只读特性使用 property() 作为 装饰器 :

class Parrot:
    def __init__(self):
        self._voltage = 100000
    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage
															

The @property 装饰器转换 voltage() 方法转换成具有相同名称的只读属性 getter,并设置文档字符串为 voltage 成 Get the current voltage (获取电流电压)。

@ getter
@ setter
@ deleter

property 对象拥有 getter , setter ,和 deleter 方法,可用作装饰器以创建将设为装饰函数,具有相应 accessor (访问器) 函数的特性副本。最好采用范例来解释这:

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
																	

此代码与第 1 范例准确等价。确保赋予额外函数相同名称如原始特性 ( x 在此情况下)。

返回特性对象也拥有属性 fget , fset ,和 fdel 对应构造函数自变量。

3.5 版改变: 特性对象的 docstring (文档字符串) 现在是可写的。

class range ( stop )
class range ( start , stop , step = 1 )

除了是函数, range 实际是不可变序列类型,如文档化在 范围 and 序列类型 — 列表、元组、范围 .

repr ( object )

返回包含对象可打印表示的字符串。对于许多类型,此函数试图返回的字符串将产生具有相同值的对象,当传递给 eval() ; otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() 方法。若 sys.displayhook() 不可访问,此函数会引发 RuntimeError .

This class has a custom representation that can be evaluated:

class Person:
   def __init__(self, name, age):
      self.name = name
      self.age = age
   def __repr__(self):
      return f"Person('{self.name}', {self.age})"
															
reversed ( seq )

返回反向 iterator . seq 必须是对象且有 __reversed__() 方法或支持序列协议 ( __len__() 方法和 __getitem__() 方法采用的整数自变量开始于 0 ).

round ( number , ndigits = None )

返回 number 四舍五入到 ndigits 精度在小数点之后。若 ndigits 被省略或为 None ,它返回最接近输入的整数。

对于内置类型支持 round() ,值被四舍五入到最接近 10 的倍数的乘幂 ndigits ;若 2 个倍数接近相等,朝偶数选择完成四舍五入 (因此,例如 round(0.5) and round(-0.5) are 0 ,和 round(1.5) is 2 )。任何整数值有效对于 ndigits (正数、零或负数)。返回值是整数若 ndigits 被省略或 None 。否则,返回值拥有相同类型如 number .

对于一般 Python 对象 number , round 委托 number.__round__ .

注意

行为在 round() 对于浮点数可能出人意料:例如, round(2.675, 2) 给出 2.67 而不是期望的 2.68 。这不是 Bug:事实是大多数十进制小数不能准确表示成浮点的结果。见 浮点算术:问题和局限性 了解更多信息。

class set
class set ( iterable )

返回新的 set 对象,可选采用元素取自 iterable . set 是内置类。见 set and 集类型 — set、frozenset 有关此类的文档编制。

对于其它容器,见内置 frozenset , list , tuple ,和 dict 类,及 collections 模块。

setattr ( object , name , value )

这搭档 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) 相当于 x.foobar = 123 .

name need not be a Python identifier as defined in 标识符和关键词 unless the object chooses to enforce that, for example in a custom __getattribute__() 或凭借 __slots__ . An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible through getattr() etc..

注意

由于 私有名称重整 发生在编译时,必须手动重整私有属性 (带有 2 前导下划线的属性) 名称,为设置它采用 setattr() .

class slice ( stop )
class slice ( start , stop , step = None )

返回 slice 对象表示的索引集指定通过 range(start, stop, step) start and step 自变量默认为 None .

start
stop
step

Slice objects have read-only data attributes start , stop ,和 step which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages.

Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i] 。见 itertools.islice() for an alternate version that returns an iterator .

Changed in version 3.12: Slice objects are now hashable (provided start , stop ,和 step are hashable).

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

返回新的排序列表,项来自 iterable .

拥有 2 个可选自变量,就必须指定关键词自变量。

key 指定一自变量函数,用于提取比较键从每个元素在 iterable (例如, key=str.lower )。默认值为 None (直接比较元素)。

reverse 是布尔值。若设为 True ,则对列表元素排序,就好像反转每一比较。

使用 functools.cmp_to_key() 以转换旧样式 cmp 函数到 key 函数。

内置 sorted() 函数保证是稳定的。排序是稳定的,若保证不改变比较相等元素的相对次序 — 这有助于多遍排序 (例如:按部门排序,然后按薪金等级排序)。

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. This will help avoid bugs when using the same data with other ordering tools such as max() that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the __gt__() 方法。

对于排序范例和简短排序教程,见 Sorting Techniques .

@ staticmethod

把方法变换成静态方法。

静态方法不接收第 1 隐含自变量。要声明静态方法,使用此习语:

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

The @staticmethod 形式是函数 装饰器 – 见 函数定义 了解细节。

可以调用静态方法在类 (譬如 C.f() ) 或在实例 (譬如 C().f() ). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such as f() ).

Python 静态方法类似 Java 或 C++ 中找到的那些。另请参阅 classmethod() 了解创建替代类构造函数的有用变体。

像所有装饰器,还可能调用 staticmethod 作为常规函数并采用其结果做一些事情。在某些情况下,若需要从类本体中引用函数且想要避免自动转换为实例方法,则需要这样做。对于这种情况,使用此习语:

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

有关静态方法的更多信息,见 标准类型层次结构 .

3.10 版改变: 静态方法现在继承方法属性 ( __module__ , __name__ , __qualname__ , __doc__ and __annotations__ ),拥有新的 __wrapped__ 属性,且现在可以按常规函数调用。

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

返回 str 版本的 object 。见 str() 了解细节。

str 是内置字符串 class 。有关字符串的一般信息,见 文本序列类型 — str .

sum ( iterable , / , start = 0 )

求和 start 和项对于 iterable 从左到右并返回总计。 iterable 的项通常是数字,且 start 值不允许是字符串。

对于某些用例,有很好的替代对于 sum() 。串联字符串序列的快速首选方式,是调用 ''.join(sequence) 。要相加具有扩展精度的浮点值,见 math.fsum() 。为串联一系列可迭代,考虑使用 itertools.chain() .

3.8 版改变: The start 参数可以指定成关键词自变量。

Changed in version 3.12: Summation of floats switched to an algorithm that gives higher accuracy on most builds.

class super
class super ( type , object_or_type = None )

返回的代理对象将方法调用委托给父级或同级类的 type 。这对访问在类中被覆盖的继承方法很有用。

The object_or_type 确定 方法分辨次序 为搜索。搜索从类右侧开始紧跟 type .

例如,若 __mro__ of object_or_type is D -> B -> C -> A -> object 和值的 type is B ,那么 super() 搜索 C -> A -> object .

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

If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) 必须为 True (这对类方法很有用)。

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

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that 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).

对于这 2 用例,典型超类调用看起来像这样:

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. One possible use case for this is calling descriptors in a parent or sibling class.

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

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

For practical suggestions on how to design cooperative classes using super() ,见 super() 使用指南 .

class tuple
class tuple ( iterable )

除了是函数, tuple 实际是不可变序列类型,如文档化在 元组 and 序列类型 — 列表、元组、范围 .

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

采用 1 自变量,返回类型为 object 。返回值为类型对象且一般来说是相同对象如返回通过 object.__class__ .

The isinstance() 内置函数推荐用于测试对象类型,因为它考虑子类。

采用 3 自变量,返回新类型对象。这本质上是动态形式的 class 语句。 name 字符串是类名并变为 __name__ 属性。 bases tuple contains the base classes and becomes the __bases__ attribute; if empty, object , the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the __dict__ attribute. The following two statements create identical type 对象:

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

另请参阅 类型对象 .

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.

另请参阅 定制类创建 .

3.6 版改变: 子类化的 type 不覆盖 type.__new__ 可能不再使用 1 自变量形式以获取对象类型。

vars ( )
vars ( object )

返回 __dict__ 属性对于模块、类、实例或任何其它对象具有 __dict__ 属性。

对象譬如模块和实例拥有可更新 __dict__ 属性;不管怎样,其它对象可以拥有写入限定在它们的 __dict__ 属性 (例如,类使用 types.MappingProxyType to prevent direct dictionary updates).

没有自变量, 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__ 属性)。

zip ( * iterables , strict = False )

并行遍历几个可迭代,从每个可迭代元素产生元组。

范例:

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

更正式: zip() returns an iterator of tuples, where the i -th tuple contains the i -th element from each of the argument iterables.

Another way to think of zip() is that it turns rows into columns, and columns into rows. 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 .

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. Python offers three different approaches to dealing with this issue:

  • 默认情况下, zip() stops when the shortest iterable is exhausted. 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. Its output is the same as regular zip() :

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

    Unlike the default behavior, it raises a ValueError if one iterable is exhausted before the others:

    >>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True):
    ...     print(item)
    ...
    (0, 'fee')
    (1, 'fi')
    (2, 'fo')
    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.

  • 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() .

边缘情况:采用一个可迭代自变量, zip() returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

提示和技巧:

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

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

    >>> 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
    																			

3.10 版改变: 添加 strict 自变量。

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

注意

这是日常 Python 编程不需要的高级函数,不像 importlib.import_module() .

此函数的援引是通过 import 语句。它可以被替换 (通过导入 builtins 模块并赋值 builtins.__import__ ) 以改变语义对于 import 语句,但这样做 strongly 不鼓励因为使用 import 挂钩通常更简单 (见 PEP 302 ) 以达到相同目标,且对假定使用中的默认 import 实现代码不会造成问题。直接使用 __import__() 也不鼓励赞成 importlib.import_module() .

函数导入模块 name ,潜在使用给定 globals and locals 以确定如何解释包上下文中的名称。 fromlist 给出应导入对象 (或子模块) 的名称从给定模块按 name 。标准实现不使用其 locals argument at all and uses its globals 仅以确定包上下文为 import 语句。

level 指定是使用绝对导入还是相对导入。 0 ( 默认) 意味着只履行绝对导入。正值 level 指示相对于模块目录要搜索的父级目录数调用 __import__() (见 PEP 328 了解细节)。

name 变量的形式为 package.module ,通常,返回顶层包 (第一点之后的名称), not 模块命名通过 name 。不管怎样,当非空 fromlist 自变量有给定,模块命名通过 name 被返回。

例如,语句 import spam 产生类似以下代码的字节码:

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

语句 import spam.ham 产生此调用:

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

注意如何 __import__() 在此返回顶层模块,因为这是被绑定到名称的对象通过 import 语句。

另一方面,语句 from spam.ham import eggs, sausage as saus 产生

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

在这里, spam.ham 模块的返回来自 __import__() 。从此对象,检索要导入的名称并分别赋值名称。

若只想按名称导入模块 (可能在包中),使用 importlib.import_module() .

3.3 版改变: 负值 level 不再被支持 (还将默认值改为 0)。

3.9 版改变: 当命令行选项 -E or -I 有使用,环境变量 PYTHONCASEOK 现被忽略。

脚注

上一话题

介绍

下一话题

内置常量

本页