🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 2. 内建函数 Python解释器内置了一些函数,它们总是可用。这里将它们按字母顺序列出。 | | | Built-in Functions | | | |-----|-----|-----|-----|-----| | [abs()](# "abs") | [divmod()](# "divmod") | [input()](# "input") | [open()](# "open") | [staticmethod()](# "staticmethod") | | [all()](# "all") | [enumerate()](# "enumerate") | [int()](# "int") | [ord()](# "ord") | [str()](# "str") | | [any()](# "any") | [eval()](# "eval") | [isinstance()](# "isinstance") | [pow()](# "pow") | [sum()](# "sum") | | [basestring()](# "basestring") | [execfile()](# "execfile") | [issubclass()](# "issubclass") | [print()](# "print") | [super()](# "super") | | [bin()](# "bin") | [file()](# "file") | [iter()](# "iter") | [property()](# "property") | [tuple()](# "tuple") | | [bool()](# "bool") | [filter()](# "filter") | [len()](# "len") | [range()](# "range") | [type()](# "type") | | [bytearray()](# "bytearray") | [float()](# "float") | [list()](# "list") | [raw_input()](# "raw_input") | [unichr()](# "unichr") | | [callable()](# "callable") | [format()](# "format") | [locals()](# "locals") | [reduce()](# "reduce") | [unicode()](# "unicode") | | [chr()](# "chr") | [frozenset()](#) | [long()](# "long") | [reload()](# "reload") | [vars()](# "vars") | | [classmethod()](# "classmethod") | [getattr()](# "getattr") | [map()](# "map") | [repr()](#) | [xrange()](# "xrange") | | [cmp()](# "cmp") | [globals()](# "globals") | [max()](# "max") | [reversed()](# "reversed") | [zip()](# "zip") | | [compile()](# "compile") | [hasattr()](# "hasattr") | [memoryview()](#) | [round()](# "round") | [__import__()](# "__import__") | | [complex()](# "complex") | [hash()](# "hash") | [min()](# "min") | [set()](#) | [apply()](# "apply") | | [delattr()](# "delattr") | [help()](# "help") | [next()](# "next") | [setattr()](# "setattr") | [buffer()](# "buffer") | | [dict()](#) | [hex()](# "hex") | [object()](# "object") | [slice()](# "slice") | [coerce()](# "coerce") | | [dir()](# "dir") | [id()](# "id") | [oct()](# "oct") | [sorted()](# "sorted") | [intern()](# "intern") | abs(*x*) 返回一个数的绝对值。参数可以是普通的整数,长整数或者浮点数。如果参数是个复数,返回它的模。 all(*iterable*) 如果*iterable*的所有元素为真(或者iterable为空), 返回True。等同于: ~~~ def all(iterable): for element in iterable: if not element: return False return True ~~~ 添加于版本2.5。 any(*iterable*) 如果*iterable*的任一元素为真,返回True。如果iterable为空,返回False。等同于: ~~~ def any(iterable): for element in iterable: if element: return True return False ~~~ 2.5版本添加。 basestring() 这个抽象类型是[str](# "str")和[unicode](# "unicode")的超类。它不能被调用或者实例化,但是可以用来测试一个对象是否是[str](# "str")或者[unicode](# "unicode")的实例。isinstance(obj,basestring)等同于isinstance(obj,(str,unicode))。 出现于版本2.3。 bin(*x*) 将一个整数转化成一个二进制字符串。结果是一个合法的Python表达式。如果*x*不是一个Python [int](# "int")对象,它必须定义一个返回整数的[__index__()](# "object.__index__")方法。 出现于版本2.6。 bool([*x*]) 将一个值转化成布尔值,使用标准的真值测试例程。如果*x*为假或者被忽略它返回[False](# "False");否则它返回[True](# "True")。[bool](# "bool")也是一个类,它是[int](# "int")的子类。[bool](# "bool")不能被继承。它唯一的实例就是[False](# "False")和[True](# "True")。 出现于版本2.2.1。 改变于版本 2.3:如果没有参数,函数返回[False](# "False")。 bytearray([*source*[, *encoding*[, *errors*]]]) 返回一个新的字节数组。[bytearray](# "bytearray")类型是一个可变的整数序列,整数范围为0 <= x < 256(即字节)。它有可变序列的大多数方法,参见[*Mutable Sequence Types*](#),同时它也有[str](# "str")类型的大多数方法,参见[*String Methods*](#)。 *source*参数可以以不同的方式来初始化数组,它是可选的: - 如果是*string*,必须指明*encoding*(以及可选的*errors*)参数;[bytearray()](# "bytearray")使用[str.encode()](# "str.encode")将字符串转化为字节数组。 - 如果是*integer*,生成相应大小的数组,元素初始化为空字节。 - 如果是遵循*buffer*接口的对象,对象的只读buffer被用来初始化字节数组。 - 如果是*iterable*,它的元素必须是整数,其取值范围为0<=x<256,用以初始化字节数组。 如果没有参数,它创建一个大小为0的数组。 出现于版本2.6。 callable(*object*) 如果*object*参数可调用,返回[True](# "True");否则返回[False](# "False")。如果返回真,对其调用仍有可能失败;但是如果返回假,对*object*的调用总是失败。注意类是可调用的(对类调用返回一个新实例);如果类实例有[__call__()](# "object.__call__")方法,则它们也是可调用的。 chr(*i*) 返回一个单字符字符串,字符的ASCII码为整数*i*。例如,chr(97)返回字符串'a'。它是[ord()](# "ord")的逆运算。参数的取值范围为[0..255]的闭区间;如果*i*超出取值范围,抛出[ValueError](# "exceptions.ValueError")。参见[unichr()](# "unichr")。 classmethod(*function*) 将*function*包装成类方法。 类方法接受类作为隐式的第一个参数,就像实例方法接受实例作为隐式的第一个参数一样。声明一个类方法,使用这样的惯例: ~~~ class C(object): @classmethod def f(cls, arg1, arg2, ...): ... ~~~ @classmethod是函数[*decorator*](#)(装饰器)参见[*Function definitions*](#)中的函数定义。 它即可以通过类来调用(如C.f()),也可以通过实例来调用(如C().f())。除了实例的类,实例本身被忽略。如果在子类上调用类方法,子类对象被传递为隐式的第一个参数。 类方法不同于C++或Java中的静态方法。如果你希望静态方法,参见这节的[staticmethod()](# "staticmethod")。 需要类方法更多的信息,参见[*The standard type hierarchy*](#)中标准类型层次部分的文档。 出现于版本2.2。 改变于版本2.4:添加了函数装饰器语法。 cmp(*x*, *y*) 比较两个对象*x*和*y*,根据结果返回一个整数。如果x<y,返回负数;如果x==y,返回0;如果x>y,返回正数。 compile(*source*, *filename*, *mode*[, *flags*[, *dont_inherit*]]) 将*source*编译成代码对象,或者AST(Abstract Syntax Tree,抽象语法树)对象。代码对象可以经由[exec](#)语句执行,或者通过调用[eval()](# "eval")演算。*source*可以是Unicode字符串,*Latin-1*编码的字符串或者AST对象。参考[ast](# "ast: Abstract Syntax Tree classes and manipulation.")模块文档以了解如何和AST对象一起使用的信息。 *filename*参数指明一个文件,从该文件中读取(源)代码;如果代码不是从文件中读入,传递一个可识别的值(一般用'<string>')。 *mode*参数指明了编译成哪一类的代码;它可以是'exec',如果*source*包含一组语句;也可以是'eval',如果是单一的表达式;或者是'single',如果是单一的交互式语句(对于最后一种情况,如果表达式语句演算成非None,它的值会被打印)。 可选的参数*flags*和*dont_inherit*控制哪些future语句(见[**PEP 236**](http://www.python.org/dev/peps/pep-0236))影响*source*的编译。如果没有这两个参数(或者都为0),使用调用compile的代码当前有效的future语句来编译source。如果给出了*flags*参数且没有给出*dont_inherit*参数(或者为0),除了本该使用的future语句之外,由*flags*参数指明的future语句也会影响编译。如果*dont_inherit*是非0整数,*flags*参数被忽略(调用compile周围的有效的future语句被忽略)。 future语句由bit位指明,这些bit可以做或运算,以指明多个语句。可以在[__future__](# "__future__: Future statement definitions")模块中,_Feature实例的compiler_flag属性找到指明功能的bit位。 如果被编译的源代码是不合法的,函数抛出[SyntaxError](# "exceptions.SyntaxError");如果源代码包含空字节,函数抛出[TypeError](# "exceptions.TypeError")。 注意 当以'single'或者'eval'模式编译多行代码字符串的时候,输入至少以一个新行结尾。这主要是便于[code](# "code: Facilities to implement read-eval-print loops.")模块检测语句是否结束。 改变于版本 2.3:添加了*flags*和*dont_inherit*参数。 改变于版本2.6:支持编译AST对象。 改变于版本2.7:允许使用Windows和Mac的新行字符。'exec'模式下的输入不需要以新行结束。 complex([*real*[, *imag*]]) 创建一个复数,它的值为*real* + *imag**j;或者将一个字符串/数字转化成一个复数。如果第一个参数是个字符串,它将被解释成复数,同时函数不能有第二个参数。第二个参数不能是字符串。每个参数必须是数值类型(包括复数)。如果*imag*被忽略,它的默认值是0,这时该函数就像是[int()](# "int"),[long()](# "long")和[float()](# "float")这样的数值转换函数。如果两个参数都被忽略,返回0j。 注意 当从字符串转化成复数的时候,字符串中+或者-两边不能有空白。例如,complex('1+2j')是可行的,但complex('1+2j')会抛出[ValueError](# "exceptions.ValueError")异常。 在[*Numeric Types — int, float, long, complex*](#)中有对复数的描述。 delattr(*object*, *name*) 这个函数和[setattr()](# "setattr")有关。参数是一个对象和一个字符串。字符串必须是对象的某个属性的名字。只要对象允许,这个函数删除该名字对应的属性。例如,delattr(x,'foobar')等同于delx.foobar。 dict(***kwarg*)dict(*mapping*, ***kwarg*)dict(*iterable*, ***kwarg*) 创建一个新字典。[dict](# "dict")对象就是字典类。参见[dict](# "dict")和[*Mapping Types — dict*](#)以得到关于该类的文档。 参见[list](# "list"),[set](# "set"),和[tuple](# "tuple")类以及[collections](# "collections: High-performance datatypes")模块了解其它的容器。 dir([*object*]) 如果没有参数,返回当前本地作用域内的名字列表。如果有参数,尝试返回参数所指明对象的合法属性的列表。 如果对象有__dir__()方法,该方法被调用且必须返回一个属性列表。这允许实现了定制化的[__getattr__()](# "object.__getattr__")或者[__getattribute__()](# "object.__getattribute__")函数的对象定制[dir()](# "dir")报告对象属性的方式。 如果对象没有提供__dir__(),同时如果对象有定义__dict__属性,dir()会先尝试从__dict__属性中收集信息,然后是对象的类型对象。结果列表没有必要是完整的,如果对象有定制化的[__getattr__()](# "object.__getattr__"),结果还有可能是不准确的。 对于不同类型的对象,默认的[dir()](# "dir")行为也不同,因为它尝试产生相关的而不是完整的信息: - 如果对象是模块对象,列表包含模块的属性名。 - 如果对象是类型或者类对象,列表包含类的属性名,及它的基类的属性名。 - 否则,列表包含对象的属性名,它的类的属性名和类的基类的属性名。 返回的列表按字母顺序排序。例如: ~~~ >>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__doc__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape(object): def __dir__(self): return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'perimeter', 'location'] ~~~ 注意 因为[dir()](# "dir")主要是为了在交互式环境下使用方便,它尝试提供有意义的名字的集合,而不是提供严格或一致定义的名字的集合,且在不同的版本中,具体的行为也有所变化。例如,如果参数是一个类,那么元类属性就不会出现在结果中。 divmod(*a*, *b*) 在长整数除法中,传入两个数字(非复数)作为参数,返回商和余数的二元组。对于混合的操作数类型,应用二元算术运算符的规则。对于一般或者长整数,结果等同于(a//b,a%b)。对于浮点数结果是(q,a%b),*q*一般是math.floor(a/b),但也可能比那小1。不管怎样,q*b+a%b非常接近于*a*,如果a%b非0,它和*b*符号相同且0<=abs(a%b)<abs(b)。 改变于版本2.3:废弃了在[divmod()](# "divmod")中使用复数。 enumerate(*sequence*, *start=0*) 返回一个枚举对象。*sequence*必须是个序列,迭代器[*iterator*](#),或者支持迭代的对象。[enumerate()](# "enumerate")返回的迭代器的next()方法返回一个元组,它包含一个计数(从*start*开始,默认为0)和从*sequence*中迭代得到的值: ~~~ >>> 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 ~~~ 出现于版本2.3。 改变于版本2.6:添加了*start*参数。 eval(*expression*[, *globals*[, *locals*]]) 参数是Unicode或者*Latin-1*编码的字符串,全局变量和局部变量可选。如果有全局变量,*globals*必须是个字典。如果有局部变量,*locals*可以是任何映射类型对象。 改变于版本2.4:在此之前*locals*需要是个字典。 *expression*参数被当作Python表达式来解析并演算(技术上来说,是个条件列表),使用*globals*和*locals*字典作为全局和局部的命名空间。如果*globals*字典存在,且缺少‘__builtins__’,在*expression*被解析之前,当前的全局变量被拷贝进*globals*。这意味着一般来说*expression*能完全访问标准[__builtin__](# "__builtin__: The module that provides the built-in namespace.")模块,且受限的环境会传播。如果*locals*字典被忽略,默认是*globals*字典。如果都被忽略,表达式在[eval()](# "eval")被调用的环境中执行。返回值是被演算的表达式的结果。语法错误报告成异常。例子: ~~~ >>> x = 1 >>> print eval('x+1') 2 ~~~ 该函数也能执行任意的代码对象(如[compile()](# "compile")返回的结果)。在这种情况下,传递代码对象而不是字符串。如果代码对象编译时*mode*参数为'exec',[eval()](# "eval")返回None。 提示:[exec](#)语句支持动态的语句执行。[execfile()](# "execfile")函数支持执行文件中的语句。[globals()](# "globals")和[locals()](# "locals")函数返回当前的全局变量和局部变量的字典,可以传递给[eval()](# "eval")或者[execfile()](# "execfile")。 参见[ast.literal_eval()](# "ast.literal_eval"),该函数能安全演算只含字面量的表达式的字符串。 execfile(*filename*[, *globals*[, *locals*]]) 该函数类似于[exec](#)语句,它解析一个文件而不是字符串。它不同于[import](#)语句的地方在于它不使用模块管理——它无条件的读入文件且不会创建一个新模块。[[1]](#) 参数是个文件名和两个可选的字典。文件被当成Python语句序列来解析并演算(类似于模块),使用*globals*和*locals*字典作为全局和局部的命名空间。如果存在,*locals*可以是任意的映射类型对象。记住在模块级别,全局和局部字典是同一个字典。如果*globals*和*locals*是两个不同的对象,代码就好象是嵌入在类定义中被执行。 改变于版本2.4:在此之前*locals*必须是个字典。 如果*locals*字典被忽略,默认是*globals*字典。如果两个字典都被忽略,表达式在[execfile()](# "execfile")被调用的环境中执行。返回None。 注意 默认的*locals*的行为和下述的[locals()](# "locals")函数一样:不应该尝试修改默认的*locals*字典。如果在[execfile()](# "execfile")函数返回后,你希望看到作用于*locals*的代码的效果,显示地传递一个*locals*字典。[execfile()](# "execfile")不能用于可靠地修改一个函数的局部变量。 file(*name*[, *mode*[, *buffering*]]) [file](# "file")类型的构造函数,进一步的描述见[*File Objects*](#)章节。构造函数的参数同下述的[open()](# "open")内置函数。 要打开一个文件,建议使用[open()](# "open")而不是直接调用该构造函数。[file](# "file")更适合于类型测试(例如,isinstance(f,file))。 出现于版本2.2。 filter(*function*, *iterable*) 构造一个列表,列表的元素来自于*iterable*,对于这些元素*function*返回真。*iterable*可以是个序列,支持迭代的容器,或者一个迭代器。如果*iterable*是个字符串或者元组,则结果也是字符串或者元组;否则结果总是列表。如果*function*是None,使用特性函数,即为假的*iterable*被移除。 注意,在function不为None的情况下,filter(function,iterable)等同于[itemforiteminiterableiffunction(item)];否则等同于[itemforiteminiterableifitem](function为None)。 参见[itertools.ifilter()](# "itertools.ifilter")和[itertools.ifilterfalse()](# "itertools.ifilterfalse"),以得到该函数的迭代器版本,以及该函数的变体(过滤*function*返回假的元素)。 float([*x*]) 将字符串或者数字转化成浮点数。如果参数是字符串,它必须包含小数或者浮点数(可以有符号),周围可以有空白。参数也可以是[+|-]nan或者[+|-]inf。其它情况下,参数可以是原始/长整数或者浮点数,(以Python的浮点数精度)返回具有相同值的浮点数。如果没有参数,返回0.0。 注意 当传递字符串时,依赖于底层的C库,可以返回NaN(Not a Number,不是一个数字)和Infinity(无穷大)这样的值。该函数接受字符串nan(NaN),inf(正无穷大)和-inf(负无穷大)。对于NaN,不区分大小写和+/-号。总是用nan,inf或者-inf来表示NaN和Infinity。 float类型描述于[*Numeric Types — int, float, long, complex*](#)。 format(*value*[, *format_spec*]) 将*value*转化成“格式化”的表现形式,格式由*format_spec*控制。对*format_spec*的解释依赖于*value*参数的类型,大多数内置类型有标准的格式化语法:[*Format Specification Mini-Language*](#)。 注意 format(value,format_spec)仅仅调用value.__format__(format_spec)。 出现于版本2.6。 frozenset([*iterable*]) 返回一个新的[frozenset](# "frozenset")对象,如果可选参数*iterable*存在,frozenset的元素来自于iterable。frozenset是个内置类。参见[frozenset](# "frozenset")和[*Set Types — set, frozenset*](#)。 关于其它容器,参见[set](# "set"),[list](# "list"),[tuple](# "tuple"),和[dict](# "dict")类,以及[collections](# "collections: High-performance datatypes")模块。 出现于版本2.4。 getattr(*object*, *name*[, *default*]) 返回*object*的属性值。*name*必须时个字符串。如果字符串时对象某个属性的名字,则返回该属性的值。例如,getattr(x,'foobar')等同于x.foobar。如果名字指明的属性不存在,且有*default*参数,default被返回;否则抛出[AttributeError](# "exceptions.AttributeError")。 globals() 返回表示当前全局符号表的字典。它总是当前模块的字典(在函数或者方法中,它指定义的模块而不是调用的模块)。 hasattr(*object*, *name*) 参数是一个对象和一个字符串。如果字符串是对象某个属性的名字,返回True;否则返回False。(实现方式为调用getattr(object,name),看它是否抛出异常)。 hash(*object*) 返回对象的hash(哈希/散列)值(如果有的话)。hash值是整数。它被用于在字典查找时快速比较字典的键。相同的数值有相同的hash(尽管它们有不同的类型,比如1和1.0)。 help([*object*]) 调用内置的帮助系统。(这个函数主要用于交互式使用。)如果没有参数,在解释器的控制台启动交互式帮助系统。如果参数是个字符串,该字符串被当作模块名,函数名,类名,方法名,关键字或者文档主题而被查询,在控制台上打印帮助页面。如果参数是其它某种对象,生成关于对象的帮助页面。 这个函数经由[site](# "site: Module responsible for site-specific configuration.")模块加入内置的命名空间。 出现于版本2.2。 hex(*x*) 将任意大小的整数转化成以“0x”打头的小写的十六进制字符串,例如: ~~~ >>> hex(255) '0xff' >>> hex(-42) '-0x2a' >>> hex(1L) '0x1L' ~~~ 如果x不是Python的[int](# "int")或者[long](# "long")对象,它必须定义__index__()方法以返回一个整数。 参见[int()](# "int"),它将十六进制字符串转化成一个整数。 注意 使用[float.hex()](# "float.hex")方法得到浮点数的十六进制字符串表示。 改变于版本2.4:在此之前只返回无符号数。 id(*object*) 返回对象的“标识”。这是一个整数(或长整数),保证在对象的生命期内唯一且不变。生命期不重叠的两个对象可以有相同的[id()](# "id")值。 **CPython实现细节:**这是对象的内存地址。 input([*prompt*]) 等同于eval(raw_input(prompt))。 该函数不会捕获用户错误。如果输入语法不合法,将抛出[SyntaxError](# "exceptions.SyntaxError")。如果演算中有错误,将抛出其它异常。 如果有装载[readline](# "readline: GNU readline support for Python. (Unix)"),[input()](# "input")将会用它来提供复杂的行编辑和历史功能。 考虑使用[raw_input()](# "raw_input")函数来得到用户的一般输入。 int(*x=0*)int(*x*, *base=10*) 将数字或字符串*x*转化成一个整数,如果没有参数则返回0。如果*x*是个数字,它可以是原始/长整数,或者浮点数。如果*x*是浮点数,则向0截断。如果参数超出了整数的范围,则返回长整数对象。 如果*x*不是个数字,或者存在*base*参数,则*x*必须是个表示以*base*为基数的[*integer literal*](#)(整数字面量)的字符串或者Unicode对象。字面量的前面可以有+或者-(中间不能有空格),周围可以有空白。以n为基数的字面量包含数字0到n-1,用a到z(或者A到Z)来表示10到35。默认的*base*是10。允许的值为0和2-36。二进制,八进制和十六进制的字面量前面可以有0b/0B,0o/0O/0,或者0x/0X,就像代码中的整数字面量一样。基数0表示严格按整数字面量来解释字符串,所以实际的基数为2,8,10或者16。 整数类型描述于[*Numeric Types — int, float, long, complex*](#)。 isinstance(*object*, *classinfo*) 如果参数*object*是参数*classinfo*的一个实例;或者是一个子类(直接的,间接的,或者[*virtual*](#)),返回真。如果*classinfo*是类型对象(新式类)而*object*是该类型对象;或者是其子类(直接的,间接的,或者[*virtual*](#)),返回真。如果*object*不是给定类型的类实例或者对象,该函数总是返回假。如果*classinfo*既不是类对象,也不是类型对象,它可以是类/类型对象的元组,或者递归包含这样的元组(不接受其它的序列类型)。如果*classinfo*不是类,类型,类/类型的元组,抛出[TypeError](# "exceptions.TypeError")异常。 改变于版本2.2:添加对类型信息的元组的支持。 issubclass(*class*, *classinfo*) 如果*class*是*classinfo*的子类(直接的,间接的,或者[*virtual*](#)) ,返回真。一个类被认为是它自己的子类。*classinfo*可以是类对象的元组,这时*classinfo*中的每个类对象都会被检查。其它情况下,抛出[TypeError](# "exceptions.TypeError")异常。 改变于版本2.3:添加对类型信息的元组的支持。 iter(*o*[, *sentinel*]) 返回一个[*iterator*](#)对象。根据有无第二个参数,对第一个参数的解释相差很大。如果没有第二个参数,*o*必须是个集合对象,要么支持迭代协议(即 [__iter__()](# "object.__iter__")方法),要么支持序列协议(即[__getitem__()](# "object.__getitem__")方法,整数参数从0开始)。如果这些协议都不支持,抛出[TypeError](# "exceptions.TypeError")。如果有第二个参数*sentinel*,*o*必须是个可调用对象。这种情况下返回的迭代,每当调用其[next()](# "iterator.next")方法时,将会调用*o*(不带参数);如果返回值等于*sentinel*,抛出[StopIteration](# "exceptions.StopIteration"),否则返回该值。 第二种形式的[iter()](# "iter")的一个有用的应用就是读一个文件的行,直到读到特定行。下面的例子读一个文件,直到[readline()](# "io.TextIOBase.readline")方法返回一个空字符串: ~~~ with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line) ~~~ 出现于版本2.2。 len(*s*) 返回对象的长度(元素的个数)。参数可以是序列(如字符串,字节,元组,列表或者范围)或者集合(如字典,集合或者固定集合)。 list([*iterable*]) 返回一个列表,其元素来自于*iterable*(保持相同的值和顺序)。*iterable*可以是个序列,支持迭代的容器,或者迭代器对象。如果*iterable*已经是个列表,返回其拷贝,类似于iterable[:]。例如,list('abc')返回['a','b','c'],list((1,2,3))返回[1,2,3]。如果没有参数,返回一个新的空的列表,[]。 [list](# "list")是可变序列类型,见文档[*Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange*](#)。关于其它容器参见内置[dict](# "dict"),[set](# "set"),和[tuple](# "tuple")类,以及[collections](# "collections: High-performance datatypes")模块。 locals() 更新并返回表示当前局部符号表的字典。当locals在函数块中而不是类块中被调用时,[locals()](# "locals")返回自由变量。 注意 不应该修改该字典的内容;所做的改变不一定会影响到解释器所用的局部和自由变量的值。 long(*x=0*)long(*x*, *base=10*) 将一个字符串或者数字转化成一个长整数。如果参数时个字符串,它必须包含一个数字,任意大小,可以有符号,周围可以有空白。*base*参数和[int()](# "int")中的一样,只有当*x*是字符串的时候才能有此参数。其它情况下,参数可以是个原始/长整数,或者浮点数,返回具有相同值的长整数。浮点数转成整数时将浮点数向零截断。如果没有参数,返回0L。 长整数类型描述于[*Numeric Types — int, float, long, complex*](#)。 map(*function*, *iterable*, *...*) 将*function*应用于*iterable*的每一个元素,返回结果的列表。如果有额外的*iterable*参数,并行的从这些参数中取元素,并调用*function*。如果一个参数比另外的要短,将以None扩展该参数元素。如果*function*是None使用特性函数;如果有多个参数,[map()](# "map")返回一元组列表,元组包含从各个参数中取得的对应的元素(某种变换操作)。*iterable*参数可以是序列或者任意可迭代对象;结果总是列表。 max(*iterable*[, *key*])max(*arg1*, *arg2*, **args*[, *key*]) 返回可迭代的对象中的最大的元素,或者返回2个或多个参数中的最大的参数。 如果有一个位置参数,*iterable*必须是个非空的可迭代对象(如非空字符串,元组或者列表)。返回可迭代对象中最大的元素。如果有2个或更多的位置参数,返回最大位置参数。 可选的*key*参数指明了有一个参数的排序函数,如list.sort()中使用的排序函数。如果有*key*参数,它必须是关键字参数(例如,max(a,b,c,key=func))。 改变于版本2.5:添加了对可选参数*key*的支持。 memoryview(*obj*) 返回给定参数的“内存视图”。参见[*memoryview type*](#)。 min(*iterable*[, *key*])min(*arg1*, *arg2*, **args*[, *key*]) 返回可迭代的对象中的最小的元素,或者返回2个或多个参数中的最小的参数。 如果有一个位置参数,*iterable*必须是个非空的可迭代对象(如非空字符串,元组或者列表)。返回可迭代对象中最小的元素。如果有2个或更多的位置参数,返回最小的位置参数。 可选的*key*参数指明了有一个参数的排序函数,如list.sort()中使用的排序函数。如果有*key*参数,它必须是关键字参数(例如,min(a,b,c,key=func))。 改变于版本2.5:添加了对可选参数*key*的支持。 next(*iterator*[, *default*]) 通过调用*iterator*的[next()](# "iterator.next")方法,得到它的下一个元素。如果有*default*参数,在迭代器迭代完所有元素之后返回该参数;否则抛出[StopIteration](# "exceptions.StopIteration")。 出现于版本2.6。 object() 返回一个新的无特征的对象。[object](# "object")是所有新式类的基类。它有对所有新式类的实例通用的方法。 出现于版本2.2。 改变于版本2.3:改函数不接受任何的参数。在以前,它接受参数,但是会被忽略掉。 oct(*x*) 将一个(任意尺寸)整数转化成一个八进制字符串。结果是一个合法的Python表达式。 改变于版本2.4:以前只返回一个无符号数字面量。 open(*name*[, *mode*[, *buffering*]]) 打开一个文件,返回一个[file](# "file")类型的对象,file类型描述于[*File Objects*](#)章节。如果文件不能打开,抛出[IOError](# "exceptions.IOError")。当要打开一个文件,优先使用[open()](# "open"),而不是直接调用[file](# "file")构造函数。 头两个参数类似于stdio‘s fopen()的参数:*name*是要打开的文件的名字,*mode*是个指示如何打开文件的字符串。 *mode*的常用值包括:'r'读文件;'w'写文件(如果文件存在则截断之);'a' 附加(在 *某些*Unix系统上意味着*所有*的写操作附加到文件的末尾,不管当前的写位置)。如果没有*mode*,默认是'r'。默认使用文本模式,它会在写文件时将'\n'字符转化成平台特定的字符,在读文件时又转回来。因此在打开二进制文件的时候,要以二进制模式打开文件,把'b'添加到*mode*值,这样可以增强可移植性。(在不区分二进制文件和文本文件的系统上,附加'b'仍然时有用的,它可以起到文档的目的。)参见下文以得到*mode*更多的可能的值。 可选的*buffering*参数指明了文件需要的缓冲大小:0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的*buffering*意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。[[2]](#) 模式'r+','w+'和'a+'打开文件以便更新(同时读写)。注意'w+'会截断文件。在区分文本文件和二进制文件的系统上,在模式中附加'b'会以二进制模式打开文件;在不区分的系统上,添加'b'没有效果。 除了标准的fopen()模式值,*mode*可以是'U'或者'rU'。构建Python时一般会添加[*universal newlines*](#)(统一新行)支持;'U'会以文本模式打开文件,但是行可以以以下字符结束:'\n'(Unix行结束符),'\r'(Macintosh惯例),或者'\r\n'(Windows惯例)。Python程序会认为它们都是'\n'。如果构建Python时没有添加统一新行的支持,*mode*'U'和普通文本模式一样。注意,这样打开的文件对象有一个叫newlines的属性,它的值是None(没有发现新行),'\n','\r','\r\n',或者是包含所有已发现的新行字符的元组。 Python要求模式字符串在去除'U'后以'r','w'或者'a'开头。 Python提供了许多文件处理模块,包括[fileinput](# "fileinput: Loop over standard input or a list of files."),[os](# "os: Miscellaneous operating system interfaces."),[os.path](# "os.path: Operations on pathnames."),[tempfile](# "tempfile: Generate temporary files and directories.")和[shutil](# "shutil: High-level file operations, including copying.")。 改变于版本2.5:引入了对模式字符串第一个字符的限制。 ord(*c*) 给定一个长度为一的字符串,如果参数是unicode对象,则返回表示字符的代码点的整数;如果参数是八位字符串,返回字节值。例如,ord('a')返回整数97,ord(u'\u2020')返回8224。它是八位字符串[chr()](# "chr")的反函数,也是unicode对象[unichr()](# "unichr")的反函数。如果参数是unicode且构建Python时添加了UCS2 Unicode支持,那么字符的码点必须在[0..65535]的闭区间;如果字符串的长度为2,则抛出[TypeError](# "exceptions.TypeError")。 pow(*x*, *y*[, *z*]) 返回*x* 的 *y*次幂;如果 *z* 提供的时候,, 返回 *x* 的 *y* 次幂,然后对  *z* 取模。(这样比 pow(x,y)%z) 更高效。两个参数的形式 pow(x,y) 与使用 操作符: x**y 是等价的。 参数必须是数字类型的。由于操作数是混合类型的,二进制计算的原因需要一些强制的规定。对于整型和长整型的操作数,计算结果和操作数(强制后的)是相同的类型。除非第二个 参数是负数。在这种情况下, 所有的参数都会被转化成浮点型,并且会返回一个浮点的结果。例如, 10**2 返回 100, 但 10**-2 返回0.01.(这个新特性被加入在Python2.2中在Python2.1和之前的版本中,如果两个参数是整型,并且第二个参数为负数的情况下,会抛出一个异常。)如果第二个参数为负数,那么第三个参数必须省略。如果提供参数 *z* , *x* and *y* 必须为整数,而且*y*要是非负整数。(这个限制是在Python2.2加入的。Python2.1以及之前的版本, 三个参数都是浮点型的pow() 版本,返回的结果依赖 平台 对于浮点数的取整情况。) print(**objects*, *sep=' '*, *end='\n'*, *file=sys.stdout*) 以sep分割,end的值结尾,将 目标对象 打印到 文件流中。*sep*, *end* 和 *file*,如果提供这三个参数的话,必须以键值的形式。 所有非键值形式提供的参数,都被转化为字符串,就像用str()转化那样。[](# "str")然后写到 文件流中,以 *sep* 分割, *end* 结尾。*sep* and *end* 都必须是字符串形式的;也可以留成 None, 这样会使用默认值。如果没有打印 *对象*, [print()](# "print") 只打印一个 结束符号 *end*. *file* 参数一定要是含有 write(string)方法的对象 ;如果该参数为空,或为None, 默认使用[sys.stdout](# "sys.stdout") 作为输出。输出缓冲方式由*file*决定。例如 ,使用file.flush() 来确保, 立即显示在屏幕上. Note This function is not normally available as a built-in since the name print is recognized as the [print](#) statement.为了使得print语句失效,而使用 [print()](# "print") 函数, 可以使用future 语句 在你的模块上面: ~~~ from __future__ import print_function ~~~ 2.6 版中新增。 property([*fget*[, *fset*[, *fdel*[, *doc*]]]]) 返回[*新式类*](#)(继承自[object](# "object")的类)的一个属性。 *fget*是用于获取属性值的函数,类似地*fset*用于设置属性,*fdel*用于删除属性。典型的用法是定义一个托管的属性:x: ~~~ class C(object): 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将调用获取函数,c.x=value调用设置函数,delc.x调用删除函数。 如果给出*doc*,它将是该属性的文档字符串。否则,该属性将拷贝*fget*的文档字符串(如果存在)。这使得用[property()](# "property")作为[*装饰器*](#)创建一个只读属性非常容易: ~~~ class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage ~~~ 将voltage()方法转换为一个与只读属性具有相同名称的获取函数。 A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.最好的解释就是使用一个例子: ~~~ class C(object): 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 ~~~ 这段代码与第一个例子完全相等。请确保给额外的函数与原始的属性相同的名字(此例中为x。) The returned property also has the attributes fget, fset, and fdel corresponding to the constructor arguments. 2.2版中新增。 2.5版中的变化:如果*doc*没有给出则使用*fget*的文档字符串。 2.6版中的变化:添加getter、setter和deleter属性。 range(*stop*)range(*start*, *stop*[, *step*]) 这是一个创建算术级数列表的通用函数。它最常用于[for](#)循环。参数必须为普通的整数。如果*step*参数省略,则默认为1。如果*start*参数省略,则默认为0。该函数的完整形式返回一个整数列表[start,start+step,start+2*step,...]。如果*step*为正,则最后一个元素start+i*step最大且小于*stop*;如果*step*为负,则最后一个元素start+i*step最小且大于*stop*。*step*必须不能为零(否则会引发[ValueError](# "exceptions.ValueError"))。示例: ~~~ >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> range(0, 30, 5) [0, 5, 10, 15, 20, 25] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> range(0) [] >>> range(1, 0) [] ~~~ raw_input([*prompt*]) 如果有*prompt*参数,则将它输出到标准输出且不带换行。该函数然后从标准输入读取一行,将它转换成一个字符串(去掉一个末尾的换行符),然后返回它。当读到EOF时,则引发[EOFError](# "exceptions.EOFError")。示例: ~~~ >>> s = raw_input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus" ~~~ 如果已经加载[readline](# "readline: GNU readline support for Python. (Unix)")模块,那么[raw_input()](# "raw_input")将用它来提供优雅的行编辑和历史功能。 reduce(*function*, *iterable*[, *initializer*]) 将带有两个参数的*function*累计地应用到*iterable*的元素上,从左向右,以致将可迭代序列reduce为一个单一的值。例如,reduce(lambdax,y:x+y,[1,2,3,4,5])相当于计算((((1+2)+3)+4)+5)。左边的参数*x*是累计之后的值,右边的参数*y*是来自*iterable*中的修改值。如果提供可选的参数*initializer*,它在计算时放在可迭代序列的最前面,并且当可迭代序列为空时作为默认值。如果*initializer*没有给出,且*iterable*只包含一个元素,将返回第一个元素。大致等同于: ~~~ def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: try: initializer = next(it) except StopIteration: raise TypeError('reduce() of empty sequence with no initial value') accum_value = initializer for x in it: accum_value = function(accum_value, x) return accum_value ~~~ reload(*module*) 重载之前已经引入过的*模块*.参数必须是一个模型对象,所以之前它必须成功导入。如果你用外部编辑器编辑了模型的源文件并且打算在不离开python解释器的情况下使用模型的新版本,reload将非常有用。返回值是该模块对象(与*module*参数相同)。 当执行reload(module)时: - python模型的代码将重新编译并且模型级的代码会重新执行,定义一系列对象,这些对象的名字和模型字典中的名字相关联。改进后的模型的 init 函数不会第二次加载。 - 跟Python其他对象一样,旧的对象只有在他们的引用计数将为0的时候被系统收回。 - 模型命名空间中的名字自动升级指向新的或者修改后的对象。 - 对旧对象的其他引用(比如模型延展的命名)不会连接到新的改进对象。每一个命名空间在被请求的时候,都必须更新。 这里有一些列的其他警告: If a module is syntactically correct but its initialization fails, the first [import](#) statement for it does not bind its name locally, but does store a (partially initialized) module object in sys.modules.To reload the module you must first [import](#) it again (this will bind the name to the partially initialized module object) before you can [reload()](# "reload") it. When a module is reloaded, its dictionary (containing the module’s global variables) is retained.Redefinitions of names will override the old definitions, so this is generally not a problem.If the new version of a module does not define a name that was defined by the old version, the old definition remains.This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a [try](#) statement it can test for the table’s presence and skip its initialization if desired: ~~~ try: cache except NameError: cache = {} ~~~ It is legal though generally not very useful to reload built-in or dynamically loaded modules, except for [sys](# "sys: Access system-specific parameters and functions."), [__main__](# "__main__: The environment where the top-level script is run.") and [__builtin__](# "__builtin__: The module that provides the built-in namespace.").In many cases, however, extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded. If a module imports objects from another module using [from](#) ...[import](#) ..., calling [reload()](# "reload") for the other module does not redefine the objects imported from it — one way around this is to re-execute the [from](#) statement, another is to use [import](#) and qualified names (*module*.*name*) instead. If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition.The same is true for derived classes. repr(*object*) 返回某个对象可打印形式的字符串。它与字符串转换式(反引号)产生的值相同。有时候能够把这个操作作为一个普通的函数访问非常有用。For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to [eval()](# "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.类可以通过定义[__repr__()](# "object.__repr__")方法控制该函数对其实例的返回。 reversed(*seq*) 返回一个反转的[*迭代器*](#)。*seq*必须是一个具有[__reversed__()](# "object.__reversed__") 方法或支持序列协议的对象(整数参数从0开始的[__len__()](# "object.__len__")方法和[__getitem__()](# "object.__getitem__") 方法)。 2.4版中新增。 2.6版中的变化:添加可以编写一个定制的[__reversed__()](# "object.__reversed__")方法的可能。 round(*number*[, *ndigits*]) 返回一个浮点型 *近似值*,保留小数点后 *ndigits* 位。如果省略*ndigits*,它默认为零。结果是一个浮点数。Values are rounded to the closest multiple of 10 to the power minus *ndigits*;if two multiples are equally close, rounding is done away from 0 (所以,例如,round(0.5)是1.0 且round(-0.5)是-1.0)。 Note 浮点数[round()](# "round")的行为可能让人惊讶,例如round(2.675,2)给出的是2.67 而不是期望的2.68。这不是一个错误:大部分十进制小数不能用浮点数精确表示,它是因为这样的一个事实的结果。更多信息,请参阅[*Floating Point Arithmetic: Issues and Limitations*](#)。 set([*iterable*]) 返回一个新的[set](# "set") 对象,其元素可以从可选的*iterable*获得。set是一个内建的类。关于该类的文档,请参阅[set](# "set")和[*集合类型 — set, frozenset*](#)。 关于其它容器请参阅内建的[frozenset](# "frozenset")、[list](# "list")、[tuple](# "tuple")和[dict](# "dict")类,还有[collections](# "collections: High-performance datatypes")模块。 2.4版中新增。 setattr(*object*, *name*, *value*) [getattr()](# "getattr")的相反操作。参数是一个对象、一个字符串和任何一个值。字符串可以是一个已存在属性的名字也可以是一个新属性的名字。该函数将值赋值给属性,只要对象允许。例如,setattr(x,'foobar',123)等同于x.foobar=123。 slice(*stop*)slice(*start*, *stop*[, *step*]) 返回一个[*slice*](#)对象,表示由索引range(start,stop,step)指出的集合。*start*和*step*参数默认为None。切片对象具有只读属性start、stop和step,它们仅仅返回参数的值(或者它们的默认值)。它们没有其他显式的函数;它是它们用于Numerical Python和其它第三方扩展。在使用扩展的索引语法时同样会生成切片对象。例如:a[start:stop:step]或a[start:stop,i]。返回迭代器的另外一个版本可以参阅[itertools.islice()](# "itertools.islice")。 sorted(*iterable*[, *cmp*[, *key*[, *reverse*]]]) 依据*iterable*中的元素返回一个新的列表。 可选参数*cmp*、*key*和*reverse*与list.sort()方法的参数含义相同(在[*可变的序列类型*](#)一节描述)。 *cmp*指定一个定制化的带有两个参数的比较函数(可迭代的元素),它应该根据第一个参数是小于、等于还是大于第二个参数返回负数、零或者正数:cmp=lambdax,y:cmp(x.lower(),y.lower())。默认值是None。 *key*指定一个带有一个参数的函数,它用于从每个列表元素选择一个比较的关键字:key=str.lower。默认值是None(直接比较元素)。 *reverse*是一个布尔值。如果设置为True,那么列表元素以反向比较排序。 通常情况下,*key*和*reverse*转换处理比指定一个等同的*cmp*函数要快得多。这是因为*cmp*为每个元素调用多次但是*key*和*reverse*只会触摸每个元素一次。使用[functools.cmp_to_key()](# "functools.cmp_to_key")来转换旧式的*cmp*函数为*key*函数。 关于排序的实例和排序的简明教程,请参阅[Sorting HowTo](http://wiki.python.org/moin/HowTo/Sorting/)。 2.4版中新增。 staticmethod(*function*) 返回*function*的一个静态方法。 静态方法不接受隐式的第一个参数。要声明静态方法,请使用下面的习惯方式: ~~~ class C(object): @staticmethod def f(arg1, arg2, ...): ... ~~~ @staticmethod形式是一个函数[*装饰器*](#) – 细节请参阅[*函数定义*](#)中函数定义的描述。 它既可以在类上调用(例如C.f())也可以在实例上调用(例如C().f())。除了它的类型,实例其他的内容都被忽略。 Python中的静态方法类似于Java或C++。关于创建类构造器的另外一种方法,请参阅[classmethod()](# "classmethod")。 更多关于静态方法的信息,请查看[*标准类型层次*](#)中标准类型层次的文档。 2.2版中新增。 2.4版中的新变化:添加函数装饰器语法。 str(*object=''*) 返回一个字符串,包含对象的友好的可打印表示形式。对于字符串,它返回字符串本身。与repr(object)的区别是str(object)不会永远试图返回一个[eval()](# "eval")可接受的字符串;它的目标是返回一个可打印的字符串。如果没有给出参数,则返回空字符串''。 关于字符串更多的信息请参阅[*序列类型 — str, unicode, list, tuple, bytearray, buffer, xrange*](#),它描述序列的函数(字符串是序列的一种),以及在[*String Methods*](#) 一节中描述的字符串自己的方法。若要输出格式化的字符串,请使用模板字符串或在[*字符串格式化操作*](#)一节中描述的%操作符。另外可参阅[*字符串服务*](#)一节。另请参阅[unicode()](# "unicode")。 sum(*iterable*[, *start*]) 将*start*以及*iterable*的元素从左向右相加并返回总和。*start*默认为0。*iterable*的元素通常是数字,start值不允许是一个字符串。 对于某些使用场景,有比[sum()](# "sum")更好的选择。连接字符串序列的首选和快速的方式是调用''.join(sequence)。如要相加扩展精度的浮点数,请参阅[math.fsum()](# "math.fsum")。若要连接一系列的可迭代量,可以考虑使用[itertools.chain()](# "itertools.chain")。 2.3版中新增。 super(*type*[, *object-or-type*]) 返回一个代理对象,这个对象指派方法给一个父类或者同*类*.这对进入类中被覆盖的继承方法非常有用。搜索顺序和 [getattr()](# "getattr") 一样。而它自己的 *类型* 则被忽略。 类型的 [__mro__](# "class.__mro__") 方法 *type* 罗列了被[getattr()](# "getattr") 和 [super()](# "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) must be true (this is useful for classmethods). Note [super()](# "super") only works for [*new-style class*](#)es. 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). For both use cases, a typical superclass call looks like this: ~~~ class C(B): def method(self, arg): super(C, self).method(arg) ~~~ Note that [super()](# "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__()](# "object.__getattribute__") method for searching classes in a predictable order that supports cooperative multiple inheritance.Accordingly, [super()](# "super") is undefined for implicit lookups using statements or operators such as super()[name]. Also note that [super()](# "super") is not limited to use inside methods.The two argument form specifies the arguments exactly and makes the appropriate references. For practical suggestions on how to design cooperative classes using [super()](# "super"), see [guide to using super()](http://rhettinger.wordpress.com/2011/05/26/super-considered-super/). 2.2版中新增。 tuple([*iterable*]) 返回一个元组,其元素及顺序与*iterable*的元素相同。*iterable*可以是一个序列、支持迭代操作的容器或迭代器对象。如果*iterable*已经是一个元组,它将被原样返回。例如,tuple('abc')返回('a','b','c'),tuple([1,2,3])返回(1,2,3)。如果没有给出参数,则返回一个空的元组()。 [tuple](# "tuple")是一个不可变序列类型,其文档在[*序列类型 — str, unicode, list, tuple, bytearray, buffer, xrange*](#)。关于其它容器,请参阅内建的[dict](# "dict")、[list](# "list")和[set](# "set")类以及[collections](# "collections: High-performance datatypes")模块。 type(*object*)type(*name*, *bases*, *dict*) 只有一个参数时,返回*object*的类型。返回值是一个类型对象。建议使用内建函数[isinstance()](# "isinstance")测试一个对象的类型。 带有三个参数时,返回一个新的类型对象。它本质上是[class](#)语句的动态形式。*name*字符串是类的名字且将成为[__name__](# "class.__name__")属性;*bases*元组逐条列举基类并成为[__bases__](# "class.__bases__")属性;*dict*字典是包含类体定义的命名空间并成为[__dict__](# "object.__dict__")属性。例如,下面的两条语句创建完全相同的[type](# "type")对象: ~~~ >>> class X(object): ... a = 1 ... >>> X = type('X', (object,), dict(a=1)) ~~~ 版本2.2中新增。 unichr(*i*) 返回Unicode码为整数*i*的Unicode字符。例如,unichr(97)返回字符串u'a'。这是Unicode字符串[ord()](# "ord")的反转。其参数合法的范围取决于Python是如何配置的 – 它可以是UCS2 [0..0xFFFF] 或者UCS4 [0..0x10FFFF]。否则引发[ValueError](# "exceptions.ValueError")。对于ASCII和8比特字符串,请参阅[chr()](# "chr")。 2.0版中新增。 unicode(*object=''*)unicode(*object*[, *encoding*[, *errors*]]) 使用下面的一种模式返回*object*的Unicode版字符串: If *encoding* and/or *errors* are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for *encoding*.The *encoding* parameter is a string giving the name of an encoding;if the encoding is not known, [LookupError](# "exceptions.LookupError") is raised.Error handling is done according to *errors*;this specifies the treatment of characters which are invalid in the input encoding.If *errors* is 'strict' (the default), a [ValueError](# "exceptions.ValueError") is raised on errors, while a value of 'ignore' causes errors to be silently ignored, and a value of 'replace' causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded.See also the [codecs](# "codecs: Encode and decode data and streams.") module. If no optional parameters are given, unicode() will mimic the behaviour of str() except that it returns Unicode strings instead of 8-bit strings.More precisely, if *object* is a Unicode string or subclass it will return that Unicode string without any additional decoding applied. For objects which provide a [__unicode__()](# "object.__unicode__") method, it will call this method without arguments to create a Unicode string.For all other objects, the 8-bit string version or representation is requested and then converted to a Unicode string using the codec for the default encoding in 'strict' mode. For more information on Unicode strings see [*Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange*](#) which describes sequence functionality (Unicode strings are sequences), and also the string-specific methods described in the [*String Methods*](#) section.To output formatted strings use template strings or the % operator described in the [*String Formatting Operations*](#) section.In addition see the [*String Services*](#) section.See also [str()](# "str"). 2.0版中新增。 2.2版中的变化:Support for [__unicode__()](# "object.__unicode__") added. vars([*object*]) 返回模块、类、实例或其它任何具有__dict__属性的对象的[__dict__](# "object.__dict__")属性。 模块和实例这样的对象具有可更新的__dict__属性;然而,其它对象可能对它们的__dict__属性具有写限制(例如,新式类使用dictproxy 来防止直接的字典更新)。 如果不带参数,则[vars()](# "vars")的行为类似[locals()](# "locals")。注意,局部字典只用于读取因为对局部字典的更新被忽略。 xrange(*stop*)xrange(*start*, *stop*[, *step*]) 该函数与[range()](# "range")非常相似,但是它返回一个[*xrange 对象*](#)而不是一个列表。这是一个惰性的序列类型,它生成与对应的列表相同的值但不会真正同时一起存储它们。[xrange()](# "xrange")相比[range()](# "range")的优点不大(因为[xrange()](# "xrange")仍然必须创建需要的值),除非在内存紧张的机器上使用一个非常大的range或者range的所有元素从不会使用(例如当循环经常被[break](#)终止)。关于xrange对象的更多对象,请参阅[*XRange 类型*](#)和[*序列类型— str, unicode, list, tuple, bytearray, buffer, xrange*](#)。 **CPython实现细节:**[xrange()](# "xrange")的设计意图是简单而快速。具体的实现可能强加各种限制以实现这点。Python的C实现限制所有的参数为C的原生长整型(Python的“短”整数),且要求元素的个数适合一个C的原生长整型。如果需要一个更大的range,可以使用[itertools](# "itertools: Functions creating iterators for efficient looping.")模块创建一个另外的版本:islice(count(start,step),(stop-start+step-1+2*(step<0))//step)。 zip([*iterable*, *...*]) 该函数返回一个元组的列表,其中第*i*个元组包含每个参数序列的第*i*个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,[zip()](# "zip")类似于带有一个初始参数为None的[map()](# "map")。只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。 可以保证迭代按从左向右的计算顺序。这使得使用zip(*[iter(s)]*n)来将一系列数据分类归并为长度为n的组成为习惯用法。 [zip()](# "zip")与 * 操作符一起可以用来unzip 一个列表: ~~~ >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> zipped [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zipped) >>> x == list(x2) and y == list(y2) True ~~~ 版本2.0中新增。 2.4版中的变化:以前,[zip()](# "zip")要求至少一个参数,且zip()将引发[TypeError](# "exceptions.TypeError")而不是一个空序列。 __import__(*name*[, *globals*[, *locals*[, *fromlist*[, *level*]]]]) 注意 与[importlib.import_module()](# "importlib.import_module")不同,这是一个高级的函数,不会在日常的Python变成中用到,。 This function is invoked by the [import](#) statement.It can be replaced (by importing the [__builtin__](# "__builtin__: The module that provides the built-in namespace.") module and assigning to __builtin__.__import__) in order to change semantics of the [import](#) statement, but nowadays it is usually simpler to use import hooks (see [**PEP 302**](http://www.python.org/dev/peps/pep-0302)).Direct use of [__import__()](# "__import__") is rare, except in cases where you want to import a module whose name is only known at runtime. The function imports the module *name*, potentially using the given *globals* and *locals* to determine how to interpret the name in a package context.The *fromlist* gives the names of objects or submodules that should be imported from the module given by *name*.The standard implementation does not use its *locals* argument at all, and uses its *globals* only to determine the package context of the [import](#) statement. *level* specifies whether to use absolute or relative imports.The default is -1 which indicates both absolute and relative imports will be attempted.0 means only perform absolute imports.Positive values for *level* indicate the number of parent directories to search relative to the directory of the module calling [__import__()](# "__import__"). When the *name* variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, *not* the module named by *name*.However, when a non-empty *fromlist* argument is given, the module named by *name* is returned. For example, the statement importspam results in bytecode resembling the following code: ~~~ spam = __import__('spam', globals(), locals(), [], -1) ~~~ The statement importspam.ham results in this call: ~~~ spam = __import__('spam.ham', globals(), locals(), [], -1) ~~~ Note how [__import__()](# "__import__") returns the toplevel module here because this is the object that is bound to a name by the [import](#) statement. On the other hand, the statement fromspam.hamimporteggs,sausageassaus results in ~~~ _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) eggs = _temp.eggs saus = _temp.sausage ~~~ Here, the spam.ham module is returned from [__import__()](# "__import__").From this object, the names to import are retrieved and assigned to their respective names. 如果你只是简单地想依据名字导入一个模块,请使用[importlib.import_module()](# "importlib.import_module")。 2.5版中的变化:添加level参数。 2.5版中的变化:添加关键字参数的支持。