2. 内置函数

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

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

返回数的绝对值。自变量可以是整数或浮点数。若自变量是复数,返回其幅度。

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 )

Convert an integer number to a binary string. The result is a valid Python expression. If x 不是 Python int 对象,它必须定义 __index__() method that returns an integer.

class bool ( [ x ] )

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

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

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

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

  • 若它是 string ,还必须给出 encoding (和可选, errors ) 参数; bytearray() then converts the string to bytes using str.encode() .
  • 若它是 integer , the array will have that size and will be initialized with null bytes.
  • 若它是对象且符合 buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
  • 若它是 iterable ,它必须是整数的可迭代在范围 0 <= x < 256 ,用作数组的初始内容。

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

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

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

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

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

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

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

callable ( object )

返回 True object 自变量看起来可调用, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling 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 ( function )

Return a class method for function .

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

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

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

It can be called either on the class (such as C.f() ) 或在实例 (譬如 C().f() )。实例被忽略,除它的类外。若派生类调用类方法,则派生类对象作为隐式第一自变量被传递。

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

For more information on class methods, consult the documentation on the standard type hierarchy in 标准类型层次结构 .

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 control which future statements (see PEP 236 ) 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__ 模块。

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

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

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

注意

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

3.2 版改变: Allowed use of Windows and Mac newlines. Also input in 'exec' 模式必须不再以换行符结束。添加 optimize 参数。

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

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 .

注意

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

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

delattr ( object , name )

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

class dict ( **kwarg )
class dict ( 映射 , **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 属性。
  • 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 类。

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

>>> 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=None , locals=None )

自变量是字符串和可选 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 lacks ‘__builtins__’, the current globals are copied into globals 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 in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

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

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() ‘s return value will be 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 ( object [ , globals [ , locals ] ] )

此函数支持 Python 代码的动态执行。 object 必须是字符串 (或代码对象)。若它是字符串,则字符串会被剖析成一套 Python 语句然后执行 (除非发生句法错误)。 [1] 若它是代码对象,只需执行它。在所有情况下,被执行代码作为文件输入都是有效的 (见参考手册 "文件输入" 章节)。注意 return and yield 语句不可以用于函数定义外,即使在代码上下文内被传递给 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, 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() .

注意

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

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

范例:

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

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

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

注意

对于对象具有自定义 __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.

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

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

hex ( x )

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”, for example:

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

If x is not a Python int object, it has to define an __index__() method that returns an integer.

另请参阅 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 实现细节: 这是对象在内存中的地址。

input ( [ prompt ] )

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

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

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

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

返回的整数对象构造自数字或字符串 x ,或返回 0 若自变量未给定。若 x is a number, return x.__int__() 。对于浮点数,这朝 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__ .

isinstance ( object , classinfo )

返回 True 若 object 自变量是实例对于 classinfo 自变量,或 (直接、间接或 virtual ) 其子类。若 object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object 是任何类型的实例。若 classinfo 不是类型 (或类型和这种元组的元组), TypeError 异常被引发。

issubclass ( class , classinfo )

返回 True 若 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() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

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

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

class list ( [ iterable ] )

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

locals ( )

更新并返回表示当前本地符号表的字典。自由变量的返回是通过 locals() 当在函数块中而不是类块中调用它时。

注意

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

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 仅关键词自变量。

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 仅关键词自变量。

next ( iterator [ , default ] )

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

class object

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

注意

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

oct ( x )

Convert an integer number to an octal string. The result is a valid Python expression. If x 不是 Python int 对象,它必须定义 __index__() method that returns an integer.

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

打开 file 并返回相应 文件对象 。若文件无法打开, OSError 被引发。

file is either a string or bytes 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. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd 被设为 False )。

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

字符 含义
'r' 打开以供读取 (默认)
'w' 打开以供写入,先截取文件
'x' 打开以供独占创建,会失败若文件已存在
'a' 打开以供写入,追加到 EOF (文件末尾) 若存在
'b' 二进制模式
't' 文本模式 (默认)
'+' 打开磁盘文件为更新 (读写)
'U' 通用换行符 模式 (弃用)

默认模式为 'r' (打开为读取文本,同义词 'rt' )。对于二进制读写访问,模式 'w+b' 打开并截取文件到 0 字节。 'r+b' 打开文件不截断。

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

注意

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

buffering 是用于设置缓冲策略的可选整数。传递 0 将关闭缓冲 (只允许在二进制模式下),1 选择行缓冲 (仅在文本模式下可用),而 > 1 的整数指示固定大小的分块缓冲 (以字节为单位)。当没有 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 . On many systems, the buffer will typically be 4096 or 8192 bytes long.
  • "交互" 文本文件 (文件 isatty() 返回 True ) use line buffering. Other text files use the policy described above for binary files.

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

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

  • 'strict' 会引发 ValueError exception if there is an encoding error. The default value of None has the same 效果。
  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.
  • 'replace' 导致置换标记 (譬如 '?' ) to be inserted where there is malformed data.
  • 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn; .
  • 'backslashreplace' replaces malformed data by Python’s backslashed 转义序列。
  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} 转义序列。

newline 控制如何 通用换行符 模式工作 (它仅应用于文本模式)。它可以为 None , '' , '\n' , '\r' ,和 '\r\n' 。其工作如下:

  • 当从流读取输入时,若 newline is None , universal newlines mode is enabled. Lines in the input can end in '\n' , '\r' ,或 '\r\n' ,且这些会被翻译成 '\n' before being returned to the caller. If it is '' , universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
  • 当写入输出到流时,若 newline is None ,任何 '\n' 写入字符被翻译成系统默认行分隔符, os.linesep 。若 newline is '' or '\n' , no translation takes place. If 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 .

3.3 版改变: The opener 参数被添加。 'x' 模式被添加。 IOError 用于被引发,它现在是别名化的 OSError . FileExistsError 现被引发若按独占创建模式打开的文件 ( 'x' ) 已存在。

3.4 版改变: 文件现在不可继承。

从 3.4 版起弃用,将在 4.0 版中移除: The 'U' 模式。

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

3.5 版改变: The 'namereplace' 错误处理程序被添加。

ord ( c )

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

pow ( x , y [ , z ] )

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

自变量必须拥有数字类型。采用混合操作数类型,会应用二进制算术运算符强制规则。对于 int 操作数,结果与操作数类型相同 (在强制后),除非第 2 自变量为负;在此情况下,所有自变量会被转换成浮点,并交付浮点结果。例如 10**2 返回 100 ,但 10**-2 返回 0.01 . If the second argument is negative, the third argument must be omitted. If z 存在, x and y must be of integer types, and y must be non-negative.

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 ‘s docstring (if it exists). This makes it possible to create read-only properties easily using 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 (文档字符串) 现在是可写的。

range ( stop )
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 (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number .

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

注意

行为在 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][, reverse] )

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

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

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower 。默认值为 None (直接比较元素)。

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

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

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

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

staticmethod ( function )

返回静态方法为 function .

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

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

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

It can be called either on the class (such as C.f() ) 或在实例 (譬如 C().f() ). The instance is ignored except for its class.

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

For more information on static methods, consult the documentation on the standard type hierarchy in 标准类型层次结构 .

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

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

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

sum ( iterable [ , start ] )

求和 start 和项对于 iterable from left to right and returns the total. start 默认为 0 iterable ‘s items are normally numbers, and the start value is not allowed to be a string.

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

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

返回的代理对象将方法调用委托给父级或同级类的 type . This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

The __mro__ 属性在 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 this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

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

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

注意, 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() 使用指南 .

tuple ( [ iterable ] )

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

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

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

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

采用 3 自变量,返回新类型对象。这本质上是动态形式的 class 语句。 name 字符串是类名并变为 __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute. For example, the following two statements create identical type 对象:

>>> class X:
...     a = 1
...
>>> X = type('X', (object,), dict(a=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.

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] Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.