内置函数

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

内置函数
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
abs ( x )

Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned. If x 定义 __abs__() , abs(x) 返回 x.__abs__() .

all ( iterable )

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

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
						
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 or \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 ( [ x ] )

返回布尔值,即: True or False . x 的转换是使用标准 真值测试过程 。若 x 为 false 或被省略,这返回 False ;否则返回 True bool 类是子类化的 int (见 数值类型 — 整数、浮点数、复数 )。它无法进一步子类化。它的唯一实例是 False and True (见 布尔值 ).

3.7 版改变: x 现在是仅位置参数。

breakpoint ( *args , **kws )

此函数将您丢进调用站点调试器。具体来说,它调用 sys.breakpointhook() ,传递 args and kws 直接通过。默认情况下, sys.breakpointhook() 调用 pdb.set_trace() 期待没有自变量。在此情况下,它纯粹是方便函数,所以不必明确导入 pdb 或如进入调试器般多代码的类型。不管怎样, sys.breakpointhook() 可以被设为其它函数且 breakpoint() will automatically call that, allowing you to drop into the debugger of choice.

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

3.7 版新增。

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 [ , encoding [ , errors ] ] ] )

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

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

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

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

callable ( object )

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

3.2 版新增: 此函数首先在 Python 3.0 被移除,然后在 Python 3.2 被带回。

chr ( i )

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

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

@ classmethod

把方法变换成类方法。

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

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

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

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

类方法不同于 C++ 或 Java 静态方法。若想要这些,见 staticmethod() .

For more information on class methods, see 标准类型层次结构 .

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 控制哪个 未来语句 affect the compilation of source . If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile() 。若 flags 自变量有给定且 dont_inherit is not (or is zero) then the future statements specified by the flags 自变量的使用,除无论如何会使用的哪些外。若 dont_inherit 是非 0 整数那么 flags argument is it – the future statements in effect around the call to compile are ignored.

Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag 属性在 _Feature 实例在 __future__ 模块。

可选自变量 flags also controls whether the compiled source is allowed to contain top-level await , async for and async with . When the bit ast.PyCF_ALLOW_TOP_LEVEL_AWAIT is set, the return code object has CO_COROUTINE set in co_code , and can be interactively executed via await eval(code_object) .

自变量 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 版改变: Allowed use of Windows and Mac newlines. Also input in 'exec' 模式必须不再以换行符结束。添加 optimize 参数。

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

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

class complex ( [ real [ , imag ] ] )

返回复数具有值 real + imag *1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float . If both arguments are omitted, returns 0j .

对于一般 Python 对象 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__() .

注意

当从字符串转换时,字符串必须不包含空白围绕中心 + or - 运算符。例如, complex('1+2j') 很好,但 complex('1 + 2j') 引发 ValueError .

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

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

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

delattr ( object , name )

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

class dict ( **kwarg )

class dict ( mapping , **kwarg )

class dict ( iterable , **kwarg )

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

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

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(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
						
eval ( 表达式 [ , globals [ , locals ] ] )

自变量是字符串和可选 globals 及 locals。若提供, globals 必须是字典。若有提供, locals 可以是任何映射对象。

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. This means that 表达式 normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed 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.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

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

This function can also be used to execute arbitrary code objects (such as those created by compile() ). 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 returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec() .

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

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

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

此函数支持 Python 代码的动态执行。 object 必须是字符串 (或代码对象)。若它是字符串,则字符串会被剖析成一套 Python 语句然后执行 (除非发生句法错误)。 1 若它是代码对象,只需执行它。在所有情况下,被执行代码作为文件输入都是有效的 (见参考手册 "文件输入" 章节)。注意 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 module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals , the code will be executed as if it were embedded in a class definition.

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

引发 审计事件 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() 返回。

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 ( [ 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 a positive or negative infinity. 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
						

这里 floatnumber 是 Python 浮点文字形式,描述在 浮点文字 . 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 被返回。

范例:

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

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

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

3.7 版改变: x 现在是仅位置参数。

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

format ( value [ , format_spec ] )

转换 value 按 "格式化" 表示,如控制通过 format_spec 。解释 format_spec 将从属其类型对于 value 自变量,不管怎样,大多数内置类型可以使用标准格式化句法: 格式规范迷你语言 .

默认 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 ] )

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

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

getattr ( object , name [ , default ] )

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

globals ( )

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

hasattr ( object , name )

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

hash ( object )

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

注意

对于对象具有自定义 __hash__() 方法,注意 hash() 基于主机位宽截取返回值。见 __hash__() 了解细节。

help ( [ object ] )

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 ( [ prompt ] )

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

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

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

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

Raises an auditing event builtins.input/result 采用结果在成功读取输入后。

class int ( [ x ] )
class int ( x , base=10 )

返回的整数对象构造自数字或字符串 x ,或返回 0 若自变量未给定。若 x 定义 __int__() , int(x) 返回 x.__int__() 。若 x 定义 __index__() ,它返回 x.__index__() 。若 x 定义 __trunc__() ,它返回 x.__trunc__() 。对于浮点数,这朝 0 截取。

x 不是数字或者若 base 有给定,那么 x 必须是字符串, bytes ,或 bytearray 实例表示 整数文字 按基数 base . Optionally, the literal can be preceded by + or - (之间没有空格) 并以空白环绕。base-n 文字由数字 0 到 n-1 组成,采用 a to z (或 A to Z ) 拥有值 10 到 35。默认 base 为 10。允许值为 0 和 2-36。Base-2、-8 和 -16 文字可以可选前缀 0b / 0B , 0o / 0O ,或 0x / 0X , as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8) .

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

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 版改变: x 现在是仅位置参数。

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

isinstance ( object , classinfo )

返回 True object 自变量是实例对于 classinfo 自变量,或 (直接、间接或 virtual ) 其子类。若 object 不是给定类型的对象,函数始终返回 False 。若 classinfo 是类型对象 (或递归,其它这种元组) 的元组,返回 True if object 是任何类型的实例。若 classinfo 不是类型 (或类型和这种元组的元组), TypeError 异常被引发。

issubclass ( class , classinfo )

返回 True if class 是子类 (直接、间接或 virtual ) of classinfo 。类被认为是自身的子类。 classinfo 可以是类对象元组,在这种情况下,每个条目在 classinfo 将被校验。在任何其它情况下, TypeError 异常被引发。

iter ( object [ , sentinel ] )

返回 iterator 对象。第一自变量的解释非常不同,从属存在的第二自变量。没有第二自变量, object 必须是支持迭代协议的集合对象 ( __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 )

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

class list ( [ iterable ] )

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

locals ( )

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

注意

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

map ( function , iterable , ... )

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

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

返回可迭代中的最大项 (或 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 版新增: The default 仅关键词自变量。

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

class memoryview ( obj )

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

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

返回可迭代中的最小项 (或 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 版新增: The default 仅关键词自变量。

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

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 octal string either with 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.getpreferredencoding(False) 被调用以获取当前区域设置编码 (为读取和写入原生字节,使用二进制模式并留下 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 若给定。

准许存在额外模式字符 'U' ,不再有任何作用,且认为已弃用。它先前是启用 通用换行符 在文本模式,这变为了 Python 3.0 的默认行为。参考文档编制 newline 参数进一步了解细节。

注意

Python 不依赖底层操作系统的文本文件概念;所有处理由 Python 本身完成,因此独立于平台。

buffering 是用于设置缓冲策略的可选整数。传递 0 将关闭缓冲 (只允许在二进制模式下),1 选择行缓冲 (仅在文本模式下可用),而 > 1 的整数指示固定大小的分块缓冲 (以字节为单位)。当没有 buffering 自变量的给定,默认缓冲策略工作如下:

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

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

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

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

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

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

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

  • 'surrogateescape' 把任何不正确字节表示成在 Unicode Private Use Area (Unicode 私有使用区域),从 U+DC80 到 U+DCFF 范围的代码点。然后,将这些私有代码点转换成相同字节,当 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.4 版起弃用,将在 3.9 版中移除: The 'U' 模式。

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

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

3.6 版改变:
ord ( c )

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

pow ( base , exp [ , mod ] )

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

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

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=sys.stdout , flush=False )

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

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

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

确定是否缓冲输出通常由 file ,但若 flush 关键词自变量为 True,强制刷新流。

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 将援引 setter 和 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 (获取电流电压)。

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

除了是函数, 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__() 方法。

reversed ( seq )

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

round ( number [ , ndigits ] )

返回 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 ( [ iterable ] )

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

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

setattr ( object , name , value )

这搭档 getattr() 。自变量是对象、字符串和任意值。字符串可以命名现有属性或新属性。函数将值赋值给属性,若提供对象允许。例如, setattr(x, 'foobar', 123) 相当于 x.foobar = 123 .

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

返回 slice 对象表示的索引集指定通过 range(start, stop, step) start and step 自变量默认为 None 。切片对象拥有只读数据属性 start , stop and step ,仅仅返回自变量值 (或它们的默认值)。它们没有其它明确功能;不管怎样,它们可用于 Numerical Python 和其它第 3 方扩展。也会生成切片对象,当使用扩展索引句法时。例如: a[start:stop:step] or a[start:stop, i] 。见 itertools.islice() 对于返回迭代器的替代版本。

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

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

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

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

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

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

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

对于排序范例和简短排序教程,见 排序怎么样 .

@ staticmethod

把方法变换成静态方法。

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

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

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

可以调用静态方法在类 (譬如 C.f() ) 或在实例 (譬如 C().f() ).

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

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

class C:
    builtin_open = staticmethod(open)
						

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

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 参数可以指定成关键词自变量。

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

返回的代理对象将方法调用委托给父级或同级类的 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 ( [ 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 ( [ 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 )

制作聚合每个可迭代元素的迭代器。

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

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

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

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

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

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

注意

这是日常 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 自变量根本,而是使用其 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)。

脚注

1

注意,剖析器只接受 Unix 风格的行尾约定。若从文件读取代码,确保使用换行符转换模式来转换 Windows 或 Mac 风格的换行符。

上一话题

介绍

下一话题

内置常量

本页