免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3813 | 回复: 0
打印 上一主题 下一主题

Python 3.1.1 中英文对照版语言参考手册 - 数据模型(上) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-29 17:14 |只看该作者 |倒序浏览
3. 数据模型(Data model)

3.1. 对象, 值和类型(Objects, values and types)

Objects are Python’s abstraction for data.  All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
conformance to Von Neumann’s model of a “stored program computer,” code is also
represented by objects.)
Python中的 对象 是对数据的抽象。Python程序中的所有数据都用对象表示,或者用对象间的关系表示(在某种意义上,
与冯–诺依曼的”存储程序计算机”模型一致,Python中连代码也是对象)。
Every object has an identity, a type and a value.  An object’s identity never
changes once it has been created; you may think of it as the object’s address in
memory.  The ‘
is
‘ operator compares the identity of two objects; the
id()
function returns an integer representing its identity (currently
implemented as its address). An object’s type is also unchangeable.
[1]
An object’s type determines the operations that the object supports (e.g., “does
it have a length?”) and also defines the possible values for objects of that
type.  The
type()
function returns an object’s type (which is an object
itself).  The value of some objects can change.  Objects whose value can
change are said to be mutable; objects whose value is unchangeable once they
are created are called immutable. (The value of an immutable container object
that contains a reference to a mutable object can change when the latter’s value
is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed.  So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.) An
object’s mutability is determined by its type; for instance, numbers, strings
and tuples are immutable, while dictionaries and lists are mutable.
每个对象都有标识、类型和值。对象一旦建立它的 标识 就不能改变了,你可以认为它就是对象的内存地址。  可以使用’
is
‘  操作符比较两个对象的标识;
id()
函数可以获得对象标识(当前是是作为地址实现的)的一个整数表示。对象的 类型 也是不可变的[1]。  对象的类型用于确定对象能够支持的操作(例如,”它有长度吗?“),同时它也定义了该种对象的取值范围。
type()
函数返回对象的类型(类型本身也是一个对象), 某些对象的 值 可以改变,值可以改变的对象称为是 可变的(mutable) ,一旦创建完成,值就不能改变的对象称为是 不可变的(immutable)
(不可变的容器对象在引用了可变对象时,当可变对象改变了时,它其实也是可变的,但仍被看作是可变对象,这是因为它所包含的对象集合是不可变的,所以不可
变对象与值不可变并不完全一样,这点比较微妙)一个对象的可变性由它的类型决定,例如数值、字符串和元组是不可变的,而字典和列表是可变的。
Objects are never explicitly destroyed; however, when they become unreachable
they may be garbage-collected.  An implementation is allowed to postpone garbage
collection or omit it altogether — it is a matter of implementation quality
how garbage collection is implemented, as long as no objects are collected that
are still reachable.  (Implementation note: CPython currently uses a
reference-counting scheme with (optional) delayed detection of cyclically linked
garbage, which collects most objects as soon as they become unreachable, but is
not guaranteed to collect garbage containing circular references.  See the
documentation of the
gc
module for information on controlling the
collection of cyclic garbage.  Other implementations act differently and CPython
may change.)
对象从来不会被显式释放,但处于不可达状态的对象会被垃圾回收掉。实现可以选择推迟垃圾回收甚至忽略掉这个过程-这是垃圾回收机制的实现质量问题。
只要还处于可达状态的对象不被回收就满足Python语言的基本要求。(实现注意:当前CPython实现使用引用计数机制和一个可选的循环垃圾延时检测
机制,它会尽快收回大部分不可达的对象,但不能保证回收含有循环引用的垃圾对象。关于如何控制循环垃圾对象回收的详细情况,可以参考
gc
模块)。
Note that the use of the implementation’s tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a ‘
try
...
except
‘ statement may keep
objects alive.
注意,实现本身使用跟踪和调试工具时可能会导致本该回收的对象不被回收。使用语句 ‘
try
...
except
‘  也可能导致保留本该回收的对象。
Some objects contain references to “external” resources such as open files or
windows.  It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a close() method. Programs are strongly recommended to explicitly
close such objects.  The ‘
try
...
finally
‘ statement
and the ‘
with
‘ statement provide convenient ways to do this.
有些对象引用了“外部”资源,例如文件或窗口。垃圾回收也释放这些资源是顺其自然的,但垃圾回收并不是保证一定会发生的,所以这样的对象显式地提供了方法释放这些资源,通常是用 close() 方法。高度推荐使用这种方法释放引用了外部资源的对象。’
try
...
finally
‘ 和 ‘
with
‘ 语句为这种方法提供了便利。
Some objects contain references to other objects; these are called containers.
Examples of containers are tuples, lists and dictionaries.  The references are
part of a container’s value.  In most cases, when we talk about the value of a
container, we imply the values, not the identities of the contained objects;
however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied.  So, if an immutable container
(like a tuple) contains a reference to a mutable object, its value changes if
that mutable object is changed.
引用了其它对象的对象叫做 容器
,容器的例子有元组、列表和字典。引用是容器值的一部分。大多数情况下,当我们谈及一个容器的值时,指的只是值,而不是被包含对象的标识符。但是,当我们
谈及容器对象可变性的时候,指的就是被直接包含的对象的标识了。因此,如果一个不可变对象(如元组)包含了可变对象,只要这个可变对象的值变了则容器的值
就也改变了。
Types affect almost all aspects of object behavior.  Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.  E.g.,
after a = 1; b = 1, a and b may or may not refer to the same object
with the value one, depending on the implementation, but after c = []; d =
[], c and d are guaranteed to refer to two different, unique, newly
created empty lists. (Note that c = d = [] assigns the same object to both
c and d.)
类型影响了对象的绝大多数行为,在某种程度上,甚至对对象标识也有重要影响。对于不可变对象,计算新值的操作符返回的实际上可能是,一个指向已存在的具有相同类型和值的对象的引用。对于可变对象来说,这是不允许的。例如:在 a = 1; b = 1 之后, a 和 b 可能指向同一个具有1值的对象,这依赖于实现。但 c = []; d =[] 之后, c 和 d 可以保证是两个不同的、独立的、新建的空列表(注意 c = d = [] 是把相同的对象赋给了c和d)。
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.),
although such additions will often be provided via the standard library instead.
以下是Python内置类型的列表,扩展模块(根据实现,可能是C、Java或者其他语言写的)可以定义其它内置类型。未来版本的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.
以下个别类型描述中可能有”特殊属性”的段落,它们是供实现访问的,不作为一般用途。这些定义在未来有可能发生改变:
NoneThis 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 访问,在许多场合里它表示无值,例如,没有显式返回值的函数会返回 None 。这个对象的真值为假。
NotImplementedThis 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 访问。如果操作数没有对应实现,数值方法和厚比较(rich comparison)方法就会可能返回这个值 (依赖于操作符,解释器然后会尝试备选操作、或者其它后备操作)。它的真值为真。
EllipsisThis type has a single value.  There is a single object with this value. This
object is accessed through the literal ... or the built-in name
Ellipsis.  Its truth value is true.
这个类型只具有一个值,并且这种类型也只有一个对象。这个对象可以通过字面值 ... 或者内置名字 Ellipsis 访问。它的真值为真。
numbers.Number
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可以区分对整数,浮点数和复数:
numbers.Integral
These represent elements from the mathematical set of integers (positive and
negative).
描述了数学上的整数集(正负数)。
There are two types of integers:
有两类整数:
Integers (
int
)
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 (
bool
)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 the integer type, 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.
布尔。这种类型表示两个真值:假(False)和真(True)。这个类型只有这两个的对象。Boolean类型是整数类型的一个子类,在绝大多数情况下,Boolean类型值的行为与0和1相似,一个例外是转换为字符串时,会分别对应 "False" 和 "True" 。
The rules for integer representation are intended to give the most meaningful
interpretation of shift and mask operations involving negative integers.
如此设计整数表示方法的一个目的是,使得负数在移位和掩码操作中能够更有意义。
numbers.Real
(
float
)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、Java实现)对你隐藏了浮点数取值范围和溢出
处理的复杂细节。Python不支持单精度浮点数,使用它的原因通常为了降低CPU负荷和节省内存,但是这个努力会被在Python中的对象处理代价所抵
消,因此没有必要同时支持两种浮点数,使Python复杂化。
numbers.Complex
(
complex
)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 获得。
SequencesThese 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.
有序类型。本类型描述的是,以非负数作为元素索引,由有限元素构成的有序集合。内置函数
len()
返回有序类型数据中的元素数。当有序类型数据的长度为 n 时,索引号为0,1, ...,  n -1。有序类型数据 a 中的项 i ,用 a 表示。
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.
个别有序类型还支持有第三个”步长”参数的 扩展片断 : a[i:j:k] 选择了所有索引 x :  x = i + n*k, n
>= 0 并且 i  x  j 。
Sequences are distinguished according to their mutability:
有序类型按照可变性可以分为:
Immutable sequencesAn 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:
以下类型是不可变序列:
StringsThe items of a string object are Unicode code units.  A Unicode code
unit is represented by a string 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
chr()
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 string method encode().
字符串对象的项是Unicode code unit。Unicode code unit由只有一项的字符串表示,每个项可以是表示Unicode ordinal的16位或者32位值( sys.maxunicode 指定了ordinal的最大值,具体值依赖于Python是如何编译的)。Unicode对象可以表示Surrogate pair,它们会被处理成两项。内置函数
chr()

ord()
可以在code unit与Unicode 3.0标准中表示unicode ordinal的非负整数之间互相转换。与其它编码的相互转换可以通过字符串方法 encode() 进行。
TuplesThe 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对象。包括多个项(两个及以上)的元组由逗号分隔的表达式列表构成。只有一项的列表( 独元 ),可以用项后加一个逗号表示(单个表达式本身并不能创建元组,因为圆括号本身也可以用于表达式的分组)。一个空元组可以用一对空圆括号表示。
BytesA bytes object is an immutable array.  The items are 8-bit bytes,
represented by integers in the range 0 b'abc' and the built-in function
bytes()
can be used to
construct bytes objects.  Also, bytes objects can be decoded to strings
via the decode() method.
字节序列。字节序列是一个不可变的数组。每项都是值在0 b'abc' )和内置函数
bytes()
可以用于构造字节对象。可以使用 decode() 方法将字节序列对象解码为字符串对象。
Mutable sequencesMutable 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 are currently two intrinsic mutable sequence types:
目前,有两种内置的可变序列对象:
ListsThe 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的列表不要求特别的写法)
Byte ArraysA bytearray object is a mutable array. They are created by the built-in
bytearray()
constructor.  Aside from being mutable (and hence
unhashable), byte arrays otherwise provide the same interface and
functionality as immutable bytes objects.
字节数组。这是一个可变数组,可以用内置函数
bytearray()
构造。除了可变性(因此,也是不可散列的),字节数组提供了与不可变的字节序列类型相同的接口。
The extension module
array
provides an additional example of a
mutable sequence type, as does the
collections
module.
扩展模块
array
提供另一种可变序列类型,模块
collections
也是如此。
Set typesThese represent unordered, finite sets of unique, immutable objects. As such,
they cannot be indexed by any subscript. However, they can be iterated over, and
the built-in function
len()
returns the number of items in a set. Common
uses for sets are fast membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.
集合类型。这个类型描述的是由有限数量的不可变对象构成的无序集合,对象不能在集合中重复。它们不能用任何索引作为下标,但它们可以被迭代,内置函数
len()
可以计算集合里的元素数。集合的常用场合是快速测试某元素是否在集合中,或者是从一个序列中删除重复元素,或者是做一些数学运算,比如求集合的交集、并集、差和对称差。
For set elements, the same immutability rules apply as for dictionary keys. Note
that numeric types obey the normal rules for numeric comparison: if two numbers
compare equal (e.g., 1 and 1.0), only one of them can be contained in a
set.
集合元素与字典键一样,都遵循相同的不可变规则。注意,数值比较结果相等的数值型对象,只会在集合中存在一个,例如, 1 和 1.0 。
There are currently two intrinsic set types:
当前有两种内置的集合类型:
SetsThese represent a mutable set. They are created by the built-in
set()
constructor and can be modified afterwards by several methods, such as
add().
集合。这表示可变集合,可以用内置函数
set()
构造,并且可以使用一系列方法修改,比如 add() 。
Frozen setsThese represent an immutable set.  They are created by the built-in
frozenset()
constructor.  As a frozenset is immutable and
hashable
, it can be used again as an element of another set, or as
a dictionary key.
冻结集合。这表示一个不可变集合。由内置函数
frozenset()
构造。这种类型的对象是不可变的,并且是
hashable
,因为它可以作为另一个集合的元素,或者作为字典健使用。
MappingsThese 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] 表示在映射类型对象 a 中选择以 k 为索引的项,这该项可以用于表达式、作为赋值语句和
del
语句的目标。内置函数
len()
返回映射对象的元素数量。
There is currently a single intrinsic mapping type:
目前只有一种内置映射类型:
DictionariesThese 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
Dictionary displays
).
字典是可变的,可以用 {...} 创建它们,参见
Dictionary displays

The extension modules
dbm.ndbm
and
dbm.gnu
provide
additional examples of mapping types, as does the
collections
module.
扩展模块
dbm.ndbm

dbm.gnu

collections
提供了其他映射类型的例子。
Callable typesThese are the types to which the function call operation (see section
调用(Calls)
) can be applied:
可调用类型。这是表示功能调用操作的类型,见
调用(Calls)

User-defined functionsA user-defined function object is created by a function definition (see
section
Function definitions
).  It should be called with an argument list
containing the same number of items as the function’s formal parameter
list.
自定义函数对象由函数定义(见
Function definitions
)创建,函数调用时参数数量,应该与定义时的形式参数量相同。
Special attributes:
特殊属性:
Attribute
Meaning

__doc__
The function’s documentation
string, or None if
unavailable
Writable
__name__
The function’s name
Writable
__module__
The name of the module the
function was defined in, or
None if unavailable.
Writable
__defaults__
A tuple containing default
argument values for those
arguments that have defaults,
or None if no arguments
have a default value
Writable
__code__
The code object representing
the compiled function body.
Writable
__globals__
A reference to the dictionary
that holds the function’s
global variables — the
global namespace of the
module in which the function
was defined.
Read-only
__dict__
The namespace supporting
arbitrary function
attributes.
Writable
__closure__
None or a tuple of cells
that contain bindings for the
function’s free variables.
Read-only
__annotations__
A dict containing annotations
of parameters.  The keys of
the dict are the parameter
names, or 'return' for
the return annotation, if
provided.
Writable
__kwdefaults__
A dict containing defaults
for keyword-only parameters.
Writable
属性
含义

__doc__
函数的文档。字符串,如果没有
的话就为 None
可写
__name__
函数名
可写
__module__
定义函数的模块名,或者如果没有
对应模块名,就为``None``
可写
__defaults__
如果任何参数有默认值,这个分组
保存默认值,否则为 None
可写
__code__
表示编译后的函数体的代码对象
可写
__globals__
函数的全局变量字典引用,即函数
定义处的全局名字空间。
只读
__dict__
支持任意函数属性的名字空间。
可写
__closure__
元组,含有函数自由变量绑定,如
果没有自由变量,就为 None
只读
__annotations__
一个含有参数注解
(annotations)的字典,键为参
数名。如果有返回值,返回值的键
为 return
可写
__kwdefaults__
只包括关键字参数默认值的字典
可写
Most of the attributes labelled “Writable” check the type of the assigned value.
以上大多数标记为“可写”的属性都会对赋的值做类型检查。
Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions.  Regular attribute
dot-notation is used to get and set such attributes. Note that the current
implementation only supports function attributes on user-defined functions.
Function attributes on built-in functions may be supported in the future.
函数对象也支持用获得和设置任意合法属性,比如可以用这种方法将函数与元信息关联起来。常规的“点+属性”就可以获取和设置这些属性。 注意,当前实现只在用户自定义函数上支持函数属性,未来版本可能会支持内置函数的函数属性。
Additional information about a function’s definition can be retrieved from its
code object; see the description of internal types below.
函数定义的其它属性可通过它的代码对象获得,可以参考下面关于内部类型的介绍。
Instance methodsAn instance method object combines a class, a class instance and any
callable object (normally a user-defined function).
实例方法对象把类、类实例和任意可调用对象(通常是用户自定义的函数)组合到了一起。
Special read-only attributes: __self__ is the class instance object,
__func__ is the function object; __doc__ is the method’s
documentation (same as __func__.__doc__); __name__ is the
method name (same as __func__.__name__); __module__ is the
name of the module the method was defined in, or None if unavailable.
只读特殊属性: __self__ 是类实例对象, __func__ 是函数对象, __doc__ 是方法的文档(与 __func__.__doc__ 相同); __name__ 是方法的名字(与 __func__.__name__ 相同); __module__ 函数定义所在的模块名字,如果没有对应模块,就为 None 。
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 or a class method object.
用户定义方法对象可以通过获取类属性(也可能是通过该类的一个实例)创建,但前提是这个属性是用户定义函数对象,或者类方法对象。
When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its
__self__ attribute is the instance, and the method object is said
to be bound.  The new method’s __func__ attribute is the original
function object.
用从类实例获取用户定义函数的方法,创建新实例方法对象的时修改,新对象的属性 __self__ 指向该类实例,这个方法称为是“被绑定的”。这个方法的属性 __func__ 指向底层的函数对象。
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 __func__ attribute of the new
instance is not the original method object but its __func__
attribute.
当用户定义方法对象是通过获取类、或者类实例的另一个方法对象创建新方法对象的时候,它的行为与函数对象的行为相同,除了新实例的属性 __func__  指向新对象本身的 __func__ ,而不是原始的方法对象。
When an instance method object is created by retrieving a class method
object from a class or instance, its __self__ attribute is the
class itself, and its __func__ attribute is the function object
underlying the class method.
当实例方法对象是通过获取类或者实例的类方法对象创建时,它的属性 __self__ 才指向类本身,属性 __func__ 指向类方法底层的函数对象。
When an instance method object is called, the underlying function
(__func__) is called, inserting the class instance
(__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).
调用实例方法对象时会调用底层的方法( __func__ ),还会把类实例( __self__ )插入到其参数列表的前面。例如,如果类 C 是定义了函数 f() ,并且 x 是 C 的一个实例,那么调用 x.f(1) 等价于调用 C.f(x,1) 。
When an instance method object is derived from a class method object, the
“class instance” stored in __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.
当实例方法对象是从类方法对象继承的时候,属性 __self__ 保存的“类实例”实际上是类自身,所以调用 x.f(1) 或 C.f(1) 等价于调用 f(C,1) ,其中 f 是底层函数。
Note that the transformation from function object to instance method
object happens each time the attribute is retrieved from the 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
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
语句(见
The yield statement
)的函数或方法叫做 generator function 。这个函数会返回一个用于继续调用这个函数体的产生器对象,使用内置函数
next()
调用这个产生器对象 next(generator) 会得到每次
yield
语句的返回值,如果函数遇到
return
语句,或者到达结束处,它就会抛出
StopIteration
异常。
Built-in functionsA 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__ ,是函数文档字符串或者 None ; __name__ 是函数名; __self__ 为 None (请留意下面关于“内置方法”的介绍); __module__ 是定义所在的模块的名字,或者是 None 。
Built-in methodsThis 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函数内。内置方法的一个例子是 alist.append() ,这里假定 alist 是一个列表对象。这时,只读特殊属性 __self__ 被设置为 列表对象 。
ClassesClasses 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.
类也是可调用的。通常用作类实例的工厂使用。不同对象间的差异可以通过重载类的方法
__new__()
做到。调用参数都会传递给  
__new__()
,但一般情况下,由
__init__()
初始化新实例。
Class InstancesInstances of arbitrary classes can be made callable by defining a
__call__()
method in their class.
通过定义
__call__()
方法,可以使任何类实例变成可调用的。
ModulesModules are imported by the
import
statement (see section
The import statement
). A module object has a
namespace implemented by a dictionary object (this is the dictionary referenced
by the __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
语句(见
The import statement
)语句导入。每个模块都有一个用字典对象实现的名字空间(在模块中定义的函数的__global__属性引用的就是这个字典)。模块属性的访问被转换成查找这个字典,例如, 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__ 是模块的文档字符串或 None 。如果模块是由文件加载的, __file__ 是对应文件的路径名,用C语言编写的静态链接进解释器的模块没有这个属性,而对于从共享库加载的模块,这个属性的值就是共享库的路径。
Custom classesCuston class types are typically created by class definitions (see section
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"] (although there are a number of
hooks which allow for other means of locating attributes). When the attribute
name is not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order which
behaves correctly even in the presence of ‘diamond’ inheritance structures
where there are multiple inheritance paths leading back to a common ancestor.
Additional details on the C3 MRO used by Python can be found in the
documentation accompanying the 2.3 release at
定制类类型。定制类,一般是由类定义创建的(见
Class definitions
)。类用字典对象实现其名字空间,对类属性的访问会转换成对该字典的查找,例如 C.x 被解释成 C.__dict__[”x”]
(但也有许多钩子机制允许我们用其它方式访问属性)。当此查找没有找到属性时,搜索会在基类中继续进行。基类中的搜索方法使用C3方法解析顺序,这种方法
即便是多重继承里出现了公共祖先类的“菱形”结构也能保持正确行为。关于Python使用的C3 MRO额外细节可以在 2.3 版本的附带文档中找到:
http://www.python.org/download/releases/2.3/mro/
.
When a class attribute reference (for class C, say) would yield a
class method object, it is transformed into an instance method object whose
__self__ attributes is C.  When it would yield a static
method object, it is transformed into the object wrapped by the static method
object. See section
实现描述符(Implementing Descriptors)
for another way in which attributes
retrieved from a class may differ from those actually contained in its
__dict__.
当一个类(假如是类 C )的属性引用会产生类方法对象时,它就会被转换成实例方法对象,并将这个对象的 __self__ 属性指向 C 。当要产生静态方法对象时,它会被转换成用静态方法对象包装的对象。另一种获取与 __dict__ 实际内容不同的属性的方法可以参考
实现描述符(Implementing Descriptors)

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__ 是基类元组(可能为空或独元),基类的顺序以定义时基类列表中的排列次序为准。 __doc__ 是类的文档字符串或者 None 。
Class instancesA 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, it is transformed into an instance method
object whose __self__ attribute is the instance.  Static method and
class method objects are also transformed; see above under “Classes”.  See
section
实现描述符(Implementing Descriptors)
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.
类实例是用类对象调用创建的。类实例有一个用字典实现的名字空间,它是进行属性搜索的第一个地方。如果属性没在那找到, 但实例的类有那个名字的属性, 就继续在类属性中查找。如果找到的是一个用户定义函数对象,它被转换成实例方法对象,这个对象的 __self__ 属性指向实例本身。静态方法和类方法对象也会按上面“Classes”中的介绍那样进行转换。另一种获取与 __dict__ 实际内容不同的属性的方法可以参考
实现描述符(Implementing Descriptors)
。如果没有找到匹配的类属性,但对象的类提供了
__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
特殊方法名(Special method names)
.
如果提供了相应特别方法的定义,类实例可以伪装成数值、有序类型或者映射类型,参见
特殊方法名(Special method names)

Special attributes: __dict__ is the attribute dictionary;
__class__ is the instance’s class.
特殊属性: __dict__ 是属性字典; __class__ 是实例的类。
FilesA 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 standard input, output and
error streams.  See
File Objects
for complete documentation of
file objects.
文件对象表示已经打开的文件。文件对象由内置函数
open()
创建,也可以由 os.popen() 、
os.fdopen()
和 socket对象的 makefile() 方法创建(其它扩展模块的方法或函数也可以)。对象 sys.stdin , sys.stdout  和  sys.stderr 被初始化为解释器的标准输入流、标准输出流和标准错误输出流。可以在
File Objects
找到文件对象的完整文档。
Internal typesA 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 objectsCode 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代码,或者称为
bytecode
。代码对象与函数对象的不同在于函数对象包含了函数全局变量的引用(函数定义所在的模块的全局变量),而代码对象不包括上下文。默认参数值也保存在函数对
象里,而不在代码对象中(因为它们表示的是运行时计算出来的值)。不像函数对象,代码对象是不可变的,并且不包括对可变对象的(直接或间接的)引用。
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 bytecode 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_argcount 是位置参数的数目(包括参数的默认值); co_nlocals 是函数使用的局部变量的数目。 co_varnames 是一个包括局部变量名的元组(从参数的名字开始); co_cellvars 是一个元组,包括由嵌套函数引用的局部变量名; 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 定义了如下标志位:如果函数使用了 *arguments 语法接收任意数目的位置参数就会把 0x04 置位;如果函数使用了 **keywords 语法接收任意数量的关键字参数,就会把 0x08 置位。
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.
“Future功能声明”( from __future__ import division )也使用了 co_flags 的标志位指出代码对象在编译时是否打开某些特定功能:如果函数是打开了future division编译的,就会把 0x2000 置位;之前版本的Python使用过位 0x10 和 0x1000 。
Other bits in co_flags are reserved for internal use.
co_flags 中其它位由解释器内部保留。
If a code object represents a function, the first item in co_consts is
the documentation string of the function, or None if undefined.
如果代码对象表示的是函数,那么 co_consts 的第一个项是函数的文档字符串,或者为 None 。
Frame objectsFrame 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_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_builtins 字典用于查找内置名字;属性 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_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 如果不是 None ,就是这个栈桢所在函数的名称(用于调试器)。属性 f_lineno 是此栈帧当前行的行号,在跟踪函数里如果写入这个属性,可以使程序跳转到新行上(只能用于最底部的栈桢),调试器可以这样实现跳转命令(即“指定下一步”语句)。
Traceback objectsTraceback 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
The try statement
.) It is accessible as the third item of the
tuple returned by sys.exc_info(). 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.
回溯对象表示一个“异常”的栈回溯。回溯对象会在发生异常时创建。当我们在栈桢内搜索异常处理器时,每当要搜索一个栈桢就会把一个回溯对象会插入到当前回溯对象的前面。在进行异常处理器时,回溯对象对程序也就可用了(参见
The try statement
)。这些回溯对象可以通过 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 objectsSlice objects are used to represent slices for
__getitem__()
methods.  They are also created by the built-in
slice()
function.
片断对象。为
__getitem__()
方法表示片断信息,也可以用内置函数
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:
片断对象支持一个方法:
slice.indices(self, length)

This method takes a single integer argument length and computes
information about the 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.
这个方法根据整数参数 length 判断片断对象是否能够描述 length 长的元素序列。它返回一个包含三个整数的元组,分别是索引 start 、 stop 和步长 step 。对于索引不足或者说越界的情况,返回值提供的是片断对象中能够提供的最大(最小)边界索引。
Static method objectsStatic 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.
静态方法对象。这种对象提供一种可以绕过上面函数对象到方法对象转换的方法。静态方法对象一般是其他对象的包装,通常是
用户定义方法。当从一个类或者类实例获取静态方法对象时,返回的对象通常是包装过的,没有经过前面介绍的其他转换。虽然它所包装的对象经常是可调用的,但
静态方法对象本身是不可调用的。静态方法对象可以用内置函数
staticmethod()
创建。
Class method objectsA 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.
类方法对象。类似于静态方法对象,也用来包装其他对象的。是从类或者类实例获取对象的另一种候选方案。获取对象的具体行为已经在 “User-defined methods”中介绍过了。类方法对象可以使用内置函数
classmethod()
创建。
3.3. 特殊方法名(Special method names)

A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Python’s approach to operator overloading,
allowing classes to define their own behavior with respect to language
operators.  For instance, if a class defines a method named
__getitem__()
,
and x is an instance of this class, then x is roughly equivalent
to type(x).__getitem__(x, i).  Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
AttributeError
or
TypeError
).
通过定义特殊方法,类能够实现某些特殊语法才能调用的操作(例如算术运算、下标及片断操作)。这是Python方式的 operator overloading ,允许类能够针对语言操作符定义自己的行为。例如,某个类定义了方法
__getitem__()
,并且 x 是这个类的实例,那么 x 就基本上等价于 type(x).__getitem__(x, i) 。除非特别标示,在没有适当定义方法的类上执行操作会导致抛出异常,一般是
AttributeError
或者
TypeError

When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled.  For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense.  (One example
of this is the NodeList interface in the W3C’s Document Object Model.)
在实现要模拟任意内置类型的类时,需要特别指出的是“模拟”只是达到了满足使用的程度,这点需要特别指出。 例如,获取某些有序类型的单个元素是正常的,但使用片断却是没有意义的(一个例子是在W3C文档对象模型中的 NodeList 接口。)
3.3.1. 基本定制(Basic customization)

object.__new__(cls[, ...])

Called to create a new instance of class cls.  
__new__()
is a static
method (special-cased so you need not declare it as such) that takes the class
of which an instance was requested as its first argument.  The remaining
arguments are those passed to the object constructor expression (the call to the
class).  The return value of
__new__()
should be the new object instance
(usually an instance of cls).
用于创建类 cls 的新实例。
__new__()
是静态方法(但你并不需要显式地这样声明),它的第一个参数是新实例的类,其余的参数就是传递给类构造器(即类调用)的那些参数。
__new__()
的返回值应该是新对象实例(一般来说是类 cls 的实例)。
Typical implementations create a new instance of the class by invoking the
superclass’s
__new__()
method using super(currentclass,
cls).__new__(cls[, ...]) with appropriate arguments and then modifying the
newly-created instance as necessary before returning it.
这个方法的典型实现是用适当的参数通过 super(currentclass,   cls).__new__(cls[, ...]) 调用父类的
__new__()
方法,在根据需要修改之后返回这个新建实例。
If
__new__()
returns an instance of cls, then the new instance’s
__init__()
method will be invoked like __init__(self[, ...]), where
self is the new instance and the remaining arguments are the same as were
passed to
__new__()
.
如果
__new__()
返回 cls 的一个实例,那么之后会用 __init__(self[, ...]) 的方式调用新实例的
__init__()
方法,其中 self 是新实例,其余参数与传递给
__new__()
的相同。
If
__new__()
does not return an instance of cls, then the new instance’s
__init__()
method will not be invoked.
如果
__new__()
没有返回 cls 的实例,就不会被调用新实例的
__init__()

__new__()
is intended mainly to allow subclasses of immutable types (like
int, str, or tuple) to customize instance creation.  It is also commonly
overridden in custom metaclasses in order to customize class creation.
引入
__new__()
主要是为了允许对不可变类型的子类作实例定制。另外,在定制化元类(metaclass)时它也经常会实现,目的是定制化类的创建。
object.__init__(self[, ...])

Called when the instance is created.  The arguments are those passed to the
class constructor expression.  If a base class has an
__init__()
method,
the derived class’s
__init__()
method, if any, must explicitly call it to
ensure proper initialization of the base class part of the instance; for
example: BaseClass.__init__(self, [args...]).  As a special constraint on
constructors, no value may be returned; doing so will cause a
TypeError
to be raised at runtime.
在创建新实例时调用。参数与传递给类构造表达式的参数相同。如果基类中定义了
__init__()
方法,那么这个实例必须显式地调用它以确保正确完成初始化过程。例如, BaseClass.__init__(self, [args...]) 。作为一个特殊限制,这个方法不能返回任何值,否则会导致在运行时抛出异常
TypeError

object.__del__(self)

Called when the instance is about to be destroyed.  This is also called a
destructor.  If a base class has a
__del__()
method, the derived class’s
__del__()
method, if any, must explicitly call it to ensure proper
deletion of the base class part of the instance.  Note that it is possible
(though not recommended!) for the
__del__()
method to postpone destruction
of the instance by creating a new reference to it.  It may then be called at a
later time when this new reference is deleted.  It is not guaranteed that
__del__()
methods are called for objects that still exist when the
interpreter exits.
在实例要被释放时被调用,也称为析构器。如果基类中也有
__del__()
方法,那么子类应该显式地调用它以确保正确删除实例的父类部分。注意,在
__del__()
里可以创建本对象的新引用来达到推迟删除的目的,但这并不是推荐做法。
__del__()
方法会在最后一个引用删除时被调用。在解释器退出时,不保证所有存活对象的
__del__()
方法都被调用。
Note
del x doesn’t directly call x.__del__() — the former decrements
the reference count for x by one, and the latter is only called when
x‘s reference count reaches zero.  Some common situations that may
prevent the reference count of an object from going to zero include:
circular references between objects (e.g., a doubly-linked list or a tree
data structure with parent and child pointers); a reference to the object
on the stack frame of a function that caught an exception (the traceback
stored in sys.exc_info()[2] keeps the stack frame alive); or a
reference to the object on the stack frame that raised an unhandled
exception in interactive mode (the traceback stored in
sys.last_traceback keeps the stack frame alive).  The first situation
can only be remedied by explicitly breaking the cycles; the latter two
situations can be resolved by storing None in sys.last_traceback.
Circular references which are garbage are detected when the option cycle
detector is enabled (it’s on by default), but can only be cleaned up if
there are no Python- level
__del__()
methods involved. Refer to the
documentation for the
gc
module for more information about how
__del__()
methods are handled by the cycle detector, particularly
the description of the garbage value.
del x 并不直接调用 x.__del__() —- 前者将引用计数减一,而后者只有在引用计数减到零时才被调用。引用计数无法达到零的一些常见情况有:对象之间的循环引用(例如,一个双链表或一个具有父子指针的树状数据结构);对出现异常的函数的栈桢上对象的引用( sys.ext_info()[2] 中的回溯对象保证了栈桢不会被删除);或者交互模式下出现未拦截异常的栈桢上的对象的引用( sys.last_traceback 中的回溯对象保证了栈桢不会被删除)。第一种情况只有能通过地打破循环才能解决。后两种情况,可以通过将 sys.last_traceback 赋予 None 解决。只有在打开循环检查器选项时(这是默认的),循环引用才能被垃圾回收机制发现,但前提是Python脚本中的
__del__()
方法不要参与进来。关于
__del__()
与循环检查器是如何相互影响的详细信息,可以参见
gc
模块的介绍,尤其是值 garbage  值的部分。
Warning
Due to the precarious circumstances under which
__del__()
methods are
invoked, exceptions that occur during their execution are ignored, and a warning
is printed to sys.stderr instead.  Also, when
__del__()
is invoked in
response to a module being deleted (e.g., when execution of the program is
done), other globals referenced by the
__del__()
method may already have
been deleted or in the process of being torn down (e.g. the import
machinery shutting down).  For this reason,
__del__()
methods
should do the absolute
minimum needed to maintain external invariants.  Starting with version 1.5,
Python guarantees that globals whose name begins with a single underscore are
deleted from their module before other globals are deleted; if no other
references to such globals exist, this may help in assuring that imported
modules are still available at the time when the
__del__()
method is
called.
因为调用
__del__()
方法时环境的不确定性,它执行时产生的异常会被忽略掉,只是在 sys.stderr 打印警告信息。另外,当因为删除模块而调用
__del__()
方法时(例如,程序退出时),有些
__del__()
所引用的全局名字可能已经删除了,或者正在删除。由于这个原因,
__del__()
方法对外部不变式的要求应该保持最小。从Python1.5开始,Python可以保证以单下划线开始的全局名字一定在其它全局名字之前从该模块中删除,如果没有其它对这种全局名字的引用,这个功能有助于保证导入的模块在调用
__del__()
时还是有效的。
object.__repr__(self)

Called by the
repr()
built-in function to compute the “official” string
representation of an object.  If at all possible, this should look like a
valid Python expression that could be used to recreate an object with the
same value (given an appropriate environment).  If this is not possible, a
string of the form  useful description...> should be returned.
The return value must be a string object. If a class defines
__repr__()
but not
__str__()
, then
__repr__()
is also used when an
“informal” string representation of instances of that class is required.
使用内置函数
repr()
计算对象的”正式”字符串表示时会调用这个方法。尽可能地,结果应该是一个能够从相同值重建这个对象的有效Python表达式(在适当环境下)。如果这不可能,也应该是返回一个形如  一些有用的描述 ...> 的字符串。返回值必须是一个字符串对象。如果类定义了
__repr__()
方法,但没有定义
__init__()
,那么
__repr__()
也用于产生类实例的“说明性” 字符串描述。
This is typically used for debugging, so it is important that the representation
is information-rich and unambiguous.
一般来说,这通常用于调试,所以描述字符串的信息丰富性和无歧义性是很重要的。
object.__str__(self)

Called by the
str()
built-in function and by the
print()
function
to compute the “informal” string representation of an object.  This differs
from
__repr__()
in that it does not have to be a valid Python
expression: a more convenient or concise representation may be used instead.
The return value must be a string object.
由内置函数
str()

print()
调用,用于计算一个对象的”说明性”字符串描述。与
__repr__()
不同,这里并不要求一定是有效的Python表达式,可以采用比较通俗简洁的表述方式。返回值必须是一个字符串对象。
object.__format__(self, format_spec)

Called by the
format()
built-in function (and by extension, the
format()
method of class
str
) to produce a “formatted”
string representation of an object. The format_spec argument is
a string that contains a description of the formatting options desired.
The interpretation of the format_spec argument is up to the type
implementing
__format__()
, however most classes will either
delegate formatting to one of the built-in types, or use a similar
formatting option syntax.
由内置函数
format()
(和
str
类的方法
format()
)调用,用来构造对象的“格式化”字符串描述。 format_spec 参数是描述格式选项的字符串。 format_spec 的解释依赖于实现
__format__()
的类型,但一般来说,大多数类要么把格式化任务转交给某个内置类型,或者使用与内置类型类似的格式化选项。
See
Format Specification Mini-Language
for a description of the standard formatting syntax.
关于标准格式语法的描述,可以参考
Format Specification Mini-Language

The return value must be a string object.
返回值必须是字符串对象。
object.__lt__(self, other)

object.__le__(self, other)

object.__eq__(self, other)

object.__ne__(self, other)

object.__gt__(self, other)

object.__ge__(self, other)

These are the so-called “rich comparison” methods. The correspondence between
operator symbols and method names is as follows: x calls x.__lt__(y),
x calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls
x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls
x.__ge__(y).
它们称为”厚比较”方法。运算符与方法名的对应关系如下: x 调用 x.__lt__(y) 、  x 调用 x.__le__(y) 、 x==y 调用 x.__eq__(y) 、 x!=y 调用  x.__ne__(y) 、 x>y 调用 x.__gt__(y) 、 x>=y 调用 x.__ge__(y) 。
A rich comparison method may return the singleton NotImplemented if it does
not implement the operation for a given pair of arguments. By convention,
False and True are returned for a successful comparison. However, these
methods can return any value, so if the comparison operator is used in a Boolean
context (e.g., in the condition of an if statement), Python will call
bool()
on the value to determine if the result is true or false.
不是所有厚比较方法都要同时实现的,如果个别厚比较方法没有实现,可以直接返回 NotImplemented 。从习惯上讲,一次成功的比较应该返回 False 或 True 。但是这些方法也可以返回任何值,所以如果比较运算发生在布尔上下文中(例如 if 语句中的条件测试),Python会在返回值上调用函数
bool()
确定返回值的真值。
There are no implied relationships among the comparison operators. The truth
of x==y does not imply that x!=y is false.  Accordingly, when
defining
__eq__()
, one should also define
__ne__()
so that the
operators will behave as expected.  See the paragraph on
__hash__()
for
some important notes on creating
hashable
objects which support
custom comparison operations and are usable as dictionary keys.
在比较运算符之间并没有潜在的相互关系。 x==y 为真并不意味着 x!=y 为假。因此,如果定义了方法
__eq__()
,那么也应该定义
__ne__()
,这样才可以得到期望的结果。关于如何创建
hashable
对象,以让其作为字典键使用,还需要参考
__hash__()
的介绍。
There are no swapped-argument versions of these methods (to be used when the
left argument does not support the operation but the right argument does);
rather,
__lt__()
and
__gt__()
are each other’s reflection,
__le__()
and
__ge__()
are each other’s reflection, and
__eq__()
and
__ne__()
are their own reflection.
没有参数交换版本的方法定义(这可以用于当左边参数不支持操作,但右边参数支持的情况)。
__lt__()

__gt__()
相互反义;  
__le__()

__ge__()
相互反义;
__eq__()

__ne__()
相互反义。
Arguments to rich comparison methods are never coerced.
传递给厚比较方法的参数不能是被自动强制类型转换的(coerced)。
To automatically generate ordering operations from a single root operation,
see the
Total Ordering recipe in the ASPN cookbook
.
关于如何从一个根操作自动生成顺序判定操作,可以参考
Total Ordering recipe in the ASPN cookbook
.
object.__hash__(self)

Called by built-in function
hash()
and for operations on members of
hashed collections including
set
,
frozenset
, and
dict
.  
__hash__()
should return an integer.  The only required
property is that objects which compare equal have the same hash value; it is
advised to somehow mix together (e.g. using exclusive or) the hash values for
the components of the object that also play a part in comparison of objects.
由内置函数
hash()
,或者是在可散列集合(hashed collections,包括
set

frozenset

dict
)成员上的操作调用。这个方法应该返回一个整数。只有一个要求,具有相同值的对象应该有相同的散列值。应该考虑以某种方式(例如排斥或)把在对象比较中起作用的部分与散列值关联起来。
If a class does not define an
__eq__()
method it should not define a
__hash__()
operation either; if it defines
__eq__()
but not
__hash__()
, its instances will not be usable as items in hashable
collections.  If a class defines mutable objects and implements an
__eq__()
method, it should not implement
__hash__()
, since the
implementation of hashable collections requires that a key’s hash value is
immutable (if the object’s hash value changes, it will be in the wrong hash
bucket).
如果类没有定义
__eq__()
方法,那么它也不应该定义
__hash__()
方法;如果一个类只定义了
__eq__()
方法,那么它是不适合作散列键的。如果可变对象实现了
__eq__()
方法,它也不应该实现
__hash__()
方法,因为可散列集合要求键值是不可变的(如果对象的散列值发生了改变,它会被放在错误的桶(bucket)中)。
User-defined classes have
__eq__()
and
__hash__()
methods
by default; with them, all objects compare unequal (except with themselves)
and x.__hash__() returns id(x).
所有用户定义类默认都定义了方法
__eq__()

__hash__()
,这样,所有对象都可以进行相等比较(除了与自身比较)。  x.__hash__() 返回 id(x) 。
Classes which inherit a
__hash__()
method from a parent class but
change the meaning of
__eq__()
such that the hash value returned is no
longer appropriate (e.g. by switching to a value-based concept of equality
instead of the default identity based equality) can explicitly flag
themselves as being unhashable by setting __hash__ = None in the class
definition. Doing so means that not only will instances of the class raise an
appropriate
TypeError
when a program attempts to retrieve their hash
value, but they will also be correctly identified as unhashable when checking
isinstance(obj, collections.Hashable) (unlike classes which define their
own
__hash__()
to explicitly raise
TypeError
).
如果子类从父类继承了方法
__hash__()
,但子类修改
__eq__()
,这时子类继承的散列值就不再正确了(例如,可能从默认的标识相等的比较切换成了值相等的比较),这可以通过显式在类定义时将
__hash__()
设置成 None 。使用这个方法,当试图使用这个子类对象作为散列键时,就会抛出
TypeError
异常,而且也可以正常通过可散列检查 isinstance(obj, collections.Hashable) (在这个函数里,这个方法与在
__hash__()
中显式抛出异常的方法是不同的)。
If a class that overrides
__eq__()
needs to retain the implementation
of
__hash__()
from a parent class, the interpreter must be told this
explicitly by setting __hash__ = .__hash__. Otherwise the
inheritance of
__hash__()
will be blocked, just as if __hash__
had been explicitly set to
None
.
如果子类修改了
__eq__()
方法,但需要保留父类的
__hash__()
,它必须显式地告诉解释器 __hash__ = .__hash__ ,否则
__hash__()
的继承会被阻止,就像设置 __hash__ 为 None 。
object.__bool__(self)

Called to implement truth value testing and the built-in operation
bool(); should return False or True.  When this method is not
defined,
__len__()
is called, if it is defined, and the object is
considered true if its result is nonzero.  If a class defines neither
__len__()
nor
__bool__()
, all its instances are considered
true.
在实现真值测试和内置操作 bool()  中调用,如果没有这个定义方法,转而使用
__len__()
。非零返回值,当作“真”。如果这两个方法都没有定义,就认为该实例为“真”。
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/42957/showart_2106783.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP