3.2 标准类型层次 The standard type hierarchy

Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).

以下是Python内建类型的一个列表, 以C语言写的扩展模块可以定义其它类型. 以后版本的Python可能会在这个类型层次中增加其它类型(例如: 有理数, 高效率存储的整数数组, 等等)

Some of the type descriptions below contain a paragraph listing `special attributes.' These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future.

有些类型描述中包括了一个列出"特殊属性"的段落, 它们提供了一些访问实现的方法而不是作为一般目的使用.这些定义可能会在未来改变.

无 None
This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don't explicitly return anything. Its truth value is false.

这个类型具有单一值, 也只有一个对象有这个值, 这个对象可以通过内建名字None访问 它在许多场合表示无值. 例如它在那些没有返回值的函数中返回. 其真值为假.

未实现 NotImplemented
This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented. Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true.

这个类型具有单一值, 也只有一个对象有这个值, 这个对象可以通过内建名字NotImplemented访问. 如果数值方法和许多比较方法的操作数未提供其实现, 它们就可能返回这个值. (解释器会试图扩展成 其它操作,或者其它退化的操作,依赖于运算符)它的真值为真.

省略 Ellipsis
This type has a single value. There is a single object with this value. This object is accessed through the built-in name Ellipsis. It is used to indicate the presence of the "..." syntax in a slice. Its truth value is true.

这个类型具有单一值, 也只有一个对象有这个值, 这个对象可以通过内建名字NotImplemented访问. 它用于指出使用在片断上的"..." 句法.其真值为真.

数值型 Numbers
These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers.

它们由数值型字面值生成,或由算术运算和内置算术函数作为值返回。 数值型对象是不可变的.一旦创建其值就不可改变.Python的数值型和数学上的数字关系非常密切,但要受到计算机的数值表达能力的限制.

Python distinguishes between integers, floating point numbers, and complex numbers:

Python 对整数,浮点数和复数区别对待:

整数 Integers
These represent elements from the mathematical set of whole numbers.

描述了数学上的整数集.

There are three types of integers:

有三种整数类型:

普通整数 Plain integers
These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation would fall outside this range, the result is normally returned as a long integer (in some cases, the exception OverflowError is raised instead). For the purpose of shift and mask operations, integers are assumed to have a binary, 2's complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).

描述了在 -2147483648 至 2147483647 范围之内的数.(这个范围可能会在本地机器字较大的机器更大些,但绝不会小.)当某个运算的结果超出了这个范围,异常OverflowError 会被抛出. 对于以移位和屏蔽为目的的运算, 整数被认为是使用32位或更多位的二进制的补码形式. 并且不为用户隐藏任何位.(就是说, 所有位的组合对应于4294967296个不同的值)  

长整数 Long integers
These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left.

长整数的表示范围在语言上是无限制的, 只受限于你的内存(虚拟内存). 对于以移位和屏蔽为目的的运算, 长整数被认为是二进制的形式, 如果 是负数,那么就被转换成二进制补码形式, 符号位向左扩展.

Booleans
These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers and the least surprises when switching between the plain and long integer domains. Any operation except left shift, if it yields a result in the plain integer domain without causing overflow, will yield the same result in the long integer domain or when using mixed operands.

整数表示法的这个规则为了使对负数操作时尽量有实际意义,至少也在普通整数和长 整数之间转换时所导致的结果不至于太过奇怪. 对于除了左移之外的操作, 只要 这些数的计算结果在整数域之中, 没有溢出, 那么它在长整数域或混合运算中也能 得到相同结果.

浮点数 Floating point numbers
These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers.

本类型表示了机器级的双精度浮点数. 是机器的体系结构和C实现的浮点数范围和控制溢出方法 屏蔽你不需知道的细节. Python不支持单精度浮点数, 使用它的原因通常是减少CPU负荷和节省内存, 但是这一节省被对象在Python中的使用开销所抵消, 因此没有必要支持两种浮点数使语言变 的复杂.

复数 Complex numbers
These represent complex numbers as a pair of machine-level double precision floating point numbers. The same caveats apply as for floating point numbers. The real and imaginary parts of a complex number z can be retrieved through the read-only attributes z.real and z.imag.

本类型描述了一对机器级的双精度浮点数, 在浮点数中的警告内容也适用于复数类型. 复数z的实部和虚部可以通过属性z.real和z.imag获得.

有序类型 Sequences
These represent finite ordered sets indexed by non-negative numbers. The built-in function len() returns the number of items of a sequence. When the length of a sequence is n, the index set contains the numbers 0, 1, ..., n-1. Item i of sequence a is selected by a[i].

本类型描述了用非负数索引的有限的有序集合. 内建函数len()返回有序类型数据中的项数 当有序类型数据的长为N时, 索引号为0,1, ..., N-1.有序类型数据A中的项I, 可以以A[I]表示.

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j. When used as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0.

有序类型也支持片断:a[i:j]可以表示满足i<=k<j的所有项a[k]. 在使用这个表达式时, 它具有相同的有 序类型, 这也隐含着索引重新从零开始计.

Some sequences also support ``extended slicing'' with a third ``step'' parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.

Sequences are distinguished according to their mutability:

有序类型按照可变性分两类:

不可变类型 Immutable sequences
An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)

一个不可变对象一旦建立其值不可能再改变(如果这个对象包括其它对象的引用, 这个被引用的对象可以是可变对象并且其值可以变化;但为该不可变对象所直接引用的对象集合是不能变的.)

The following types are immutable sequences:

以下类型是不可变类型:

字符串 Strings
The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file.

字符串的项是字符. 没有单独的字符类型, 一个字符可以表达成只有一个项的 串.字符描述成八比特(至少)字节. 内建函数chr()和ord()在字符和非负整数字 节值表示之间切换. 在值0-127之间的字符通常描述成ASCII值, 但值的解释依 赖于应用程序.字符串类型也用于表示字节数组, 例如, 保存从文件读出的内容.

(On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions chr() and ord() implement a mapping between ASCII and EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?)

(在那些本地字符集不是ASCII的系统上,字符串可能使用EBCDIC作为其内部表示方案. 已提供了函数chr()和ord()在ASCII和EBCDIC之间进行互换, 并且串的比较是按照 ASCII序的, 或者你有更好的主意?)

Unicode Unicode
The items of a Unicode object are Unicode code units. A Unicode code unit is represented by a Unicode object of one item and can hold either a 16-bit or 32-bit value representing a Unicode ordinal (the maximum value for the ordinal is given in sys.maxunicode, and depends on how Python is configured at compile time). Surrogate pairs may be present in the Unicode object, and will be reported as two separate items. The built-in functions unichr() and ord() convert between code units and nonnegative integers representing the Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to other encodings are possible through the Unicode method encode and the built-in function unicode().

每个Unicode对象的项是Unicode字符, 一个Unicode字符表示成一个只有一 项的Unicode对象, 并且它是一个16比特的值可以保存Unicode序数. 内建函数 unichr()和ord()在字符和定义在Unicode 3.0 标准中非负的Unicode序数之间 互换.与其它编码集转换是可能的, 可以通过Unicode方法encode()和内建方法unicode().

元组 Tuples
The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a `singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.

元组对象的项可以是做任意的Python对象. 具有两个或多个项的元组是用逗号分隔开表达式列表. 只有一项的列表(独元??)其项可以后缀一个逗号使其成为满足要求元组要求的表达式(一个表达式本身不能创建一个元组,因为圆括号本身用于表达式的分组).一个空元组可以以一对空圆括号表示.

可变对象 Mutable sequences
Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and del (delete) statements.

可变对象可以在其创建后改变, 其下标表示和片断表示可以作为赋值语句和del语句的对象

There is currently a single intrinsic mutable sequence type:

目前只有一种可变类型.

列表 Lists
The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)

列表对象的项可以是任意类型的Python对象. 列表对象是在方括号之间的用逗号分开的表达式表. (注意,形成长度为0或者1的链表不要求特别的写法)

The extension module arrayprovides an additional example of a mutable sequence type.

扩展模块array提供了另一个可变有序类型的例子

映射类型 Mappings
These represent finite sets of objects indexed by arbitrary index sets. The subscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len() returns the number of items in a mapping.

本类型描述了可以是由任意类型作索引的有限对象集合.下标表示法a[k]从映射类型对象中选择一个由k索引的项, 它们可以用作赋值语句和del语句的目标. 内建函数len()返回映射对象的项的个数.

There is currently a single intrinsic mapping type:

当前只有一个内置的映射类型:

字典 Dictionaries
These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key's hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.

本类型表达了几乎是任意类型对象都可作索引的有限对象集合.不可接受的键值仅仅是那些包括有列表和字典的值,或那些是通过值比较而不是通过对象标识符比较的类型的值.其原因是字典的高效实现要求键的哈希值保持不变. 用于键值的数值型在比较时使用通常的规则:如果两值相等(如:1和1.0), 那么它们可以互换地索引相同的字典项.

Dictionaries are mutable; they can be created by the {...} notation (see section 5.2.5, ``Dictionary Displays'').

字典是可变的, 它们由...语法创建,(详见5.2.5, ``字典的显示'').

The extension modules dbm gdbm bsddbprovide additional examples of mapping types.

扩展模块dbm, gdbm和bsddb提供了另外的映射类型的例子.

可调用类型 Callable types
These are the types to which the function call operation (see section 5.3.4, ``Calls'') can be applied:

这是一个可用的函数调用操作类型, 详见5.3.4, ``调用'')

用户自定义函数 User-defined functions
A user-defined function object is created by a function definition (see section 7.5, ``Function definitions''). It should be called with an argument list containing the same number of items as the function's formal parameter list.

一个自定义函数对象由函数定义(见7.5, "函数定义"). 创建在函数调用时应该与定义时的形式参数相同数目参数.

Special attributes: func_doc or __doc__ is the function's documentation string, or None if unavailable; func_name or __name__ is the function's name; __module__ is the name of the module the function was defined in, or None if unavailable; func_defaults is a tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value; func_code is the code object representing the compiled function body; func_globals is (a reference to) the dictionary that holds the function's global variables -- it defines the global namespace of the module in which the function was defined; func_dict or __dict__ contains the namespace supporting arbitrary function attributes; func_closure is None or a tuple of cells that contain bindings for the function's free variables.

特殊属性:func_doc or __doc__ 是函数的文档串,如果无效,就是None. func_defaults是一个包括有参数中设有默认值的元组;func_name 或__name__是函数名. func_code是一个编译后的代码对象; func_globals是一个引用,指向保存了函数的全局变量的字典 -- 如果你在函数所在模块中定义了全局变量的话.func_dict或__dict__包括了支持任意函数属性的名字空间;func_closure 要么是None, 要么是包括有函数自由变量捆绑的单元的元组.<最后两个属性这里译的可能不对>

Of these, func_code, func_defaults, func_doc/__doc__, and func_dict/__dict__ may be writable; the others can never be changed. Additional information about a function's definition can be retrieved from its code object; see the description of internal types below.

其中,func_code, func_defaults,func_closure, func_doc和func_dict/__dict__是可以写的;其它则不能改动. 关于函数的定义你可以由它的代码对象得到;见下面的关于内部对象的描述.

用户自定义方法 User-defined methods
A user-defined method object combines a class, a class instance (or None) and any callable object (normally a user-defined function).

用户自定义方法合并了一个类, 一个类实例(或None)和任何可调用对象(一般是用户自定义函数).

Special read-only attributes: im_self is the class instance object, im_func is the function object; im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods; __doc__ is the method's documentation (same as im_func.__doc__); __name__ is the method name (same as im_func.__name__); __module__ is the name of the module the method was defined in, or None if unavailable. Changed in version 2.2: im_self used to refer to the class that defined the method.

特殊的只读的属性:im_self是类实例对象, im_func是函数对象; im_class是对于捆绑的方法 , 它是im_self的类; 对于自由方法, 它是其所要求的类. __doc__是其方法的文档(与 im_func.__doc__相同), __name__是方法名(与im_func.__name__相同) 2.2版本中变化: im_self用于指出定义方法的类.

Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object.

方法也支持访问(不是设置)的其实际所调用的函数的任意属性.

User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.

When a user-defined method object is created by retrieving a user-defined function object from a class, its im_self attribute is None and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its im_self attribute is the instance, and the method object is said to be bound. In either case, the new method's im_class attribute is the class from which the retrieval takes place, and its im_func attribute is the original function object.

用户自定义方法可以用两种方法创建: 在获得是用户自定义函数对象的所属类的属性时; 或者在获得一个用户自定义函数对象的类实例的属性时. 在第一个情况(类属性)下,im_self 属性的值是None, 并且该方法称为是自由的. 后一种情况(实例属性)是, 属性是该实例, 并且 该方法称为是捆绑的.例如, C是一个具有方法f() 的类,C.f() 并不意味着一个的方法对象f.但 是它指的是自由的方法对象m, 其中m.im_class属性为C, m.im_func为f(), 并且m.im_self为None. 当x是C的一个实例时,x.f指出一个捆绑的方法对象m, 其m.im_class为C, m_im_func是f(), 并且 m.im_self是x.

When a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the im_func attribute of the new instance is not the original method object but its im_func attribute.

When a user-defined method object is created by retrieving a class method object from a class or instance, its im_self attribute is the class itself (the same as the im_class attribute), and its im_func attribute is the function object underlying the class method.

When an unbound user-defined method object is called, the underlying function (im_func) is called, with the restriction that the first argument must be an instance of the proper class (im_class) or of a derived class thereof.

当调用某个自由的用户自定义的方法(im_func)对象时,有一个限制,其第一个参数必须是适 当的类实例(im_class)或者是由它继承而来的的类的实例.

When a bound user-defined method object is called, the underlying function (im_func) is called, inserting the class instance (im_self) in front of the argument list. For instance, when C is a class which contains a definition for a function f(), and x is an instance of C, calling x.f(1) is equivalent to calling C.f(x, 1).

当一个捆绑的用户自定义的方法调用时,实际调用的是im_func, 并且在其参数表前部而插入类实例 (im_self).例如,当类C包括了一个函数定义f(), 并且x是一个C的实例, 调用x.f(1), 相当于C.f(x,1)

When a user-defined method object is derived from a class method object, the ``class instance'' stored in im_self will actually be the class itself, so that calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.

Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.

Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.

生成器函数 Generator functions
A function or method which uses the yield statement (see section 6.8, ``The yield statement'') is called a generator function. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator's next() method will cause the function to execute until it provides a value using the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned.

一个使用yield的语句(见6.8yield 语句)的方法或函数, 它叫做生成器函数. 这样的函数, 在返回后, 通常返回一个迭代子对象, 一个可以用于执行函数的对象.调用对象的next()方法会引起函数的执行直到其使用yield语句返回 一个值. 当函数在执行到return语句时, 或在末尾结束时, 会抛出异常StopIteration, 此时迭代器也到达了返回值集合的结尾。

内建函数 Built-in functions
A built-in function object is a wrapper around a C function. Examples of built-in functions are len() and math.sin() (math is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: __doc__ is the function's documentation string, or None if unavailable; __name__ is the function's name; __self__ is set to None (but see the next item); __module__ is the name of the module the function was defined in or None if unavailable.

一个内建函数就是一个C函数的包装, 例如内建函数len()和math.sin() (math是标准的内建模块) 参数的类型和数目都由C函数检测.特殊的只读属性: __doc__是函数的文档串(如果有效的话). __name__是函数名, __self__设为None(见下述).

内建方法 Built-in methods
This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is alist.append(), assuming alist is a list object. In this case, the special read-only attribute __self__ is set to the object denoted by list.

这实际上是内建函数的一个不同的包装而已. 此时传递给C函数一个对象作为隐含的参数.例如,内建 方法list.append()假定list是一个列表对象,此时特殊只读属性__self__指定为对象list.

类 Class Types
Class types, or ``new-style classes,'' are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override __new__(). The arguments of the call are passed to __new__() and, in the typical case, to __init__() to initialize the new instance.

Classic Classes
Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class's __init__() method if it has one. Any arguments are passed on to the __init__() method. If there is no __init__() method, the class must be called without arguments.

类对象下面会说到, 当一个类对象被调用时,一个类实例被创建并返回.这里隐含着调用__init__ 方法(如果它有的话), 任何参数都有会被传递到__init__中.如果类没有__init__方法, 它在调用时, 就不能指定参数.

类实例 Class instances
Class instances are described below. Class instances are callable only when the class has a __call__() method; x(arguments) is a shorthand for x.__call__(arguments).

类实例将在下面详述, 类实例仅仅在类具有__call__方法时, 才是可调用的.x(arguments) 只是x.__call__(arguments)的缩写形式.

模块 Modules
Modules are imported by the import statement (see section 6.12, ``The import statement'').A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the func_globals attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.__dict__["x"]. A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is done).

模块可以由import语句(见import语句). 一个模块有一个名字空间, 用字典对象实现的(在模块中定义的函数可以通过func_globals属性来访问这个字典).属性的访问被翻译 成查找这个字典. 例如, m.x 等价于m.__dict__["x"]. 模块对象并不包含用来初始化该模块的代码对象。) (因为一旦初始化完成它就不再需要了.)

Attribute assignment updates the module's namespace dictionary, e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".

属性的赋值更新模块的名字空间, 例如m.x=1等价于m.__dict__["x"]=1.

Special read-only attribute: __dict__ is the module's namespace as a dictionary object.

特殊只读属性:__dict__是字典形式的模块名字空间.

Predefined (writable) attributes: __name__ is the module's name; __doc__ is the module's documentation string, or None if unavailable; __file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

预定义的可写属性:__name__是模块名;__doc__是模块的文档串, 如果无效就为Nome. 如果模块装载自某文件, __file__是被装载模块的文件路径名, 因为C模块不提供些属性, 该模块已连接至解释器中, 对于那些从共享库装载的模块, 这个属性是那些共享库的路径.

类 Classes
Class objects are created by class definitions (see section 7.6, ``Class definitions''). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., "C.x" is translated to "C.__dict__["x"]". When the attribute name is not found there, the attribute search continues in the base classes. The search is depth-first, left-to-right in the order of occurrence in the base class list.

类对象由类定义创建(见7.6 类定义).一个类有一个用字典对象实现的名字空间. 类属性的访问可以转换成对该字典的查找.例如"C.x"被解释成"C.__dic__["x"]".当属性名未找到时,继续在基类中查找. 查找是深度优先的,由左至右的在基类列表中按出现的次序搜索. 当引用一个类属性时, 如果其实际是指出的一个用户自定义函数对象, 它被转换成自由的用户自定义方法对象(见上). 这个方法的im_class属性就是被该被初始化的属性引用的所在类.

When a class attribute reference (for class C, say) would yield a user-defined function object or an unbound user-defined method object whose associated class is either C or one of its base classes, it is transformed into an unbound user-defined method object whose im_class attribute is C. When it would yield a class method object, it is transformed into a bound user-defined method object whose im_class and im_self attributes are both C. When it would yield a static method object, it is transformed into the object wrapped by the static method object. See section 3.3.2 for another way in which attributes retrieved from a class may differ from those actually contained in its __dict__.

Class attribute assignments update the class's dictionary, never the dictionary of a base class.

类属性的赋值会更新类的字典, 而不是基类的字典.

A class object can be called (see above) to yield a class instance (see below).

一个类对象可以创建(见上), 这样会产生一个类实例(下述).

Special attributes: __name__ is the class name; __module__ is the module name in which the class was defined; __dict__ is the dictionary containing the class's namespace; __bases__ is a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list; __doc__ is the class's documentation string, or None if undefined.

特殊属性: __name__是类名, __module_是类所定义的模块名; __dict__是包括类名字空间的字典. __bases__是一个元组(可能是None或独元), 包括其基类, 以基类列表中它们的排列次序出现. __doc__ 是类的文档串, 如果无效, 它就是None.

类实例 Class instances
A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance's class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object or an unbound user-defined method object whose associated class is the class (call it C) of the instance for which the attribute reference was initiated or one of its bases, it is transformed into a bound user-defined method object whose im_class attribute is C whose im_self attribute is the instance. Static method and class method objects are also transformed, as if they had been retrieved from class C; see above under ``Classes''. See section 3.3.2 for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class's __dict__. If no class attribute is found, and the object's class has a __getattr__() method, that is called to satisfy the lookup.

类实例可以通过调用一个类对象来创建, 类实例可以有一个用字典实现的名字空间, 它只由搜索属性范围的第一个结果构成. 如果属性没在那找到, 并且实例的类有那个名字的属性, 就继续在类属性中寻找. 如果找到的是一个用户自定义函数对象(而不是其它情况), 它被转换成自由的用户自定义方法对象, 这个方法的im_class属性是该被初始化的属性引用的所在类. 如果没有类属性找到, 并且类有方法__getattr__(), 那么就调用它来满足查找请求.

Attribute assignments and deletions update the instance's dictionary, never a class's dictionary. If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instance dictionary directly.

属性赋值和删除会更新实例目录, 而不是类的字典. 如果类具有方法__setattr__()或__delattr__(), 则它们会在更新类实例属性调用, 而不是直接更新.

Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. See section 3.3, ``Special method names.''

Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. See section 3.3, ``Special method names.''

Special attributes: __dict__ is the attribute dictionary; __class__ is the instance's class.

特殊属性: __dict__是属性字典;__class__是实例的类.

文件 Files
A file object represents an open file. File objects are created by the open() built-in function, and also by os.popen(), os.fdopen(), and the makefile()method of socket objects (and perhaps by other functions or methods provided by extension modules). The objects sys.stdin, sys.stdout and sys.stderr are initialized to file objects corresponding to the interpreter's standardinput, output and error streams. See the Python Library Reference for complete documentation of file objects.

一个文件描述了一个打开的文件.文件由内建函数open()创建,也可以由方法os.popen(), os.fdopen() 套接口对象的makefile()方法(也可能由其它扩展模块的方法或函数)创建.对象sys.stdin和sys.stdout及 sys.stderr被相应地初始化成解释器的标准输入流, 标准输出流, 标准错误输出流.关于文件对象的完整文档,详见Python 库参考

内部类型 Internal types
A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness.

有少部分由解释器内部使用的类型,暴露给了用户.它们的定义可能会在未来的解释器版本中改变,但都会在这儿提及.

代码对象 Code objects
Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function's globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.

代码对象表达了字节编译过的可执行Python代码,或者叫字节码.代码对象和函数对象的不同在于函数对象包括了一个外在的全局变量引用(其所定义的模块),而代码对象不包括上下文.默认参数值存入函数对象中,而代码对象则不(因为它们的值由运行时计算).不像函数对象,代码是不可改变的,并且不包括对可变对象的引用.

Special read-only attributes: co_name gives the function name; co_argcount is the number of positional arguments (including arguments with default values); co_nlocals is the number of local variables used by the function (including arguments); co_varnames is a tuple containing the names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that are referenced by nested functions; co_freevars is a tuple containing the names of free variables; co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from byte code offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size (including local variables); co_flags is an integer encoding a number of flags for the interpreter.

特殊属性:co_name给出了函数名; co_argument是位置参数的数目(包括有默认值的参数); co_nlocals是函数中局部变量的数目. co_varnames是一个包括局部变量名的元组(从参数名开始); co_callvars是一个元组, 包括由嵌套函数所引用局部变量名; co_freevals包括了既不是局部变量也不是全局变量的;co_code 包括了编译过的字节码指令序列的字符串; co_consts包括字节码中使用的字面值的元组; co_names包括字节码中使用的名字的元组;co_filename包括着编译过的字节码文件名; co_firstlineno是函数首行行号; co_lnotab是一个字符串, 是字节码偏移到行号的映射(详见解释器代码);co_stacksize是所需要的堆栈尺寸(包括局部变量);co_flags是一个整数, 其解释成为许多解释器的标志.

The following flag bits are defined for co_flags: bit 0x04 is set if the function uses the "*arguments" syntax to accept an arbitrary number of positional arguments; bit 0x08 is set if the function uses the "**keywords" syntax to accept arbitrary keyword arguments; bit 0x20 is set if the function is a generator.

以下标志位由co_flags定义:如果函数使用"*参数"语法来接受任意数目的位置参数就置位0x04;如果函数使用"**keywords"语法来接受任意数量的关键字参数, 就置位0x08.其它位为内部使用, 或留作后用. 如果函数是允许作用域嵌套条件下编译的,则置位0x10; 如果代码表达的是一个函数,则co_const的第一项是该函数的文档串,如果未定义, 它就是None.

Future feature declarations ("from __future__ import division") also use bits in co_flags to indicate whether a code object was compiled with a particular feature enabled: bit 0x2000 is set if the function was compiled with future division enabled; bits 0x10 and 0x1000 were used in earlier versions of Python.

Other bits in co_flags are reserved for internal use.

Ifa code object represents a function, the first item in co_consts is the documentation string of the function, or None if undefined.

堆栈结构对象 Frame objects
Frame objects represent execution frames. They may occur in traceback objects (see below).

堆栈结构对象描述了可执行结构.它们会在跟踪回溯对象中出现(下述).

Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used for global variables; f_builtins is used for built-in (intrinsic) names; f_restricted is a flag indicating whether the function is executing in restricted execution mode; f_lasti gives the precise instruction (this is an index into the bytecode string of the code object).

特殊只读属性:f_back指出前一个堆栈结构(向着调用者的方向), 如果位于堆栈的底部它就是None; f_code指出本结构中能执行的代码对象.f_locals是用于查找局部变量的字典;f_globals用于全局变量; f_builtin用于内建名字;f_restricted是一个标志, 用于指出代码是否以受限方式执行. f_lineno给出行号,f_lasti给出精确的指令(是一个代码对象的字符串的索引).

Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); f_exc_type, f_exc_value, f_exc_traceback represent the most recent exception caught in this frame; f_lineno is the current line number of the frame -- writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to f_lineno.

特殊可写属性:f_trace, 如果非空, 就是从每个源代码行的开始处调用的函数(用于调试器). f_exc_type, f_exc_value, f_exc_traceback 表述了在这个结构中所捕捉到的的最后的异常.

跟踪回溯对象 Traceback objects
Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section 7.4, ``The try statement.'') It is accessible as sys.exc_traceback, and also as the third item of the tuple returned by sys.exc_info(). The latter is the preferred interface, since it works correctly when the program is using multiple threads. When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback.

跟踪回溯对象描述一个异常的栈回溯, 跟踪回溯对象在异常发生时创建, 在展开可执行堆栈搜索异常处理器时, 每个展开层的跟踪回溯对象插进当前跟踪回溯对象的前面.在遇到异常处理器时, 跟踪回溯对象也对程序有效了.(见7.4 try 语句) 它可以由sys.exc_traceback访问, 也可以由sys.exc_info()返回的元组的第三项访问到.后一种是推荐的接口, 因为它也可以使用多线程的程序中工作良好. 当程序中未包括适当的异常处理器, 跟踪回溯对象就被打印到标准错误输出流上.如果工作在交互方式上, 它也可以通过sys.last_traceback.

Special read-only attributes: tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None if there is no next level; tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.

特殊只读属性:tb_text是堆栈的下一层(向着异常发生的那一层结构), 或者如果没有下一层, 就为None. tb_frame指出当前层次的可执行结构; tb_lineno给出异常发生的行号; tb_lasti指出精确的指令; 如果异常发生在没有except或finally子句匹配的try语句中的话, 这里的行号和指令可能与结构中的行号和指令不同.

片断对象 Slice objects
Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function.

片断对象在使用扩展片断句法时描述片断.这是一个使用两个冒号的片断, 或者是用冒号分开的多个片断. 例如, [i:j:step], a[i:j, k:l], 或 a[..., i:j]), 它们也可以由内建函数slice()创建.

Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type.

特殊只读属性:start是下界, stop是上界, step是步进值, 如果在片断中忽略了它, 就是None.这些属性可以任意类型.

Slice objects support one method:

indices( self, length)
This method takes a single integer argument length and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the start and stop indices and the step or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices. New in version 2.3.

Static method objects
Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in staticmethod() constructor.

Class method objects
A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. The behaviour of class method objects upon such retrieval is described above, under ``User-defined methods''. Class method objects are created by the built-in classmethod() constructor.