5. 内置类型

以下部分描述了解释器中内置的标准类型。

注解

Historically (until release 2.2), Python’s built-in types have differed from user-defined types because it was not possible to use the built-in types as the basis for object-oriented inheritance. This limitation no longer exists.

The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions.

Some operations are supported by several object types; in particular, practically all objects can be compared, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function). The latter function is implicitly used when an object is written by the print() function.

5.1. 逻辑值检测

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. 1

All other values are considered true — so objects of many types are always true.

产生布尔值结果的运算和内置函数总是返回 0False 作为假值,1True 作为真值,除非另行说明。 (重要例外:布尔运算 orand 总是返回其中一个操作数。)

5.2. Boolean Operations — and, or, not

这些属于布尔运算,按优先级升序排列:

运算

结果:

注释

x or y

if x is false, then y, else x

(1)

x and y

if x is false, then x, else y

(2)

not x

if x is false, then True, else False

(3)

注释:

  1. 这是个短路运算符,因此只有在第一个参数为假值时才会对第二个参数求值。

  2. 这是个短路运算符,因此只有在第一个参数为真值时才会对第二个参数求值。

  3. not 的优先级比非布尔运算符低,因此 not a == b 会被解读为 not (a == b)a == not b 会引发语法错误。

5.3. 比较运算

Comparison operations are supported by all objects. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

此表格汇总了比较运算:

运算

含义

注释

<

严格小于

<=

小于或等于

>

严格大于

>=

大于或等于

==

等于

!=

不等于

(1)

is

对象标识

is not

否定的对象标识

注释:

  1. != can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=.

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method or the __cmp__() method.

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines either enough of the rich comparison methods (__lt__(), __le__(), __gt__(), and __ge__()) or the __cmp__() method.

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

Two more operations with the same syntactic priority, in and not in, are supported only by sequence types (below).

5.4. Numeric Types — int, float, long, complex

There are four distinct numeric types: plain integers, long integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of plain integers. Plain integers (also just called integers) are implemented using long in C, which gives them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value for the current platform, the minimum value is -sys.maxint - 1). Long integers have unlimited precision. Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in sys.float_info. Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number z, use z.real and z.imag. (The standard library includes additional numeric types, fractions that hold rationals, and decimal that hold floating-point numbers with user-definable precision.)

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an 'L' or 'l' suffix yield long integers ('L' is preferred because 1l looks too much like eleven!). Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending 'j' or 'J' to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule. 2 The constructors int(), long(), float(), and complex() can be used to produce numbers of a specific type.

All built-in numeric types support the following operations. See 幂运算符 and later sections for the operators’ priorities.

运算

结果:

注释

x + y

xy 的和

x - y

xy 的差

x * y

xy 的乘积

x / y

xy 的商

(1)

x // y

(floored) quotient of x and y

(4)(5)

x % y

remainder of x / y

(4)

-x

x 取反

+x

x 不变

abs(x)

x 的绝对值或大小

(3)

int(x)

x 转换为整数

(2)

long(x)

x converted to long integer

(2)

float(x)

x 转换为浮点数

(6)

complex(re,im)

一个带有实部 re 和虚部 im 的复数。im 默认为0。

c.conjugate()

conjugate of the complex number c. (Identity on real numbers)

divmod(x, y)

(x // y, x % y)

(3)(4)

pow(x, y)

xy 次幂

(3)(7)

x ** y

xy 次幂

(7)

注释:

  1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.

  2. Conversion from floats using int() or long() truncates toward zero like the related function, math.trunc(). Use the function math.floor() to round downward and math.ceil() to round upward.

  3. See 内置函数 for a full description.

  4. 2.3 版后已移除: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate.

  5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.

  6. float 也接受字符串 “nan” 和附带可选前缀 “+” 或 “-” 的 “inf” 分别表示非数字 (NaN) 以及正或负无穷。

    2.6 新版功能.

  7. Python 将 pow(0, 0)0 ** 0 定义为 1,这是编程语言的普遍做法。

All numbers.Real types (int, long, and float) also include the following operations:

运算

结果:

math.trunc(x)

x 截断为 Integral

round(x[, n])

x rounded to n digits, rounding ties away from zero. If n is omitted, it defaults to 0.

math.floor(x)

the greatest integer as a float <= x

math.ceil(x)

the least integer as a float >= x

5.4.1. 整数类型的按位运算

Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value (this assumes a sufficiently large number of bits that no overflow occurs during the operation).

二进制按位运算的优先级全都低于数字运算,但又高于比较运算;一元运算 ~ 具有与其他一元算术运算 (+ and -) 相同的优先级。

此表格是以优先级升序排序的按位运算列表:

运算

结果:

注释

x | y

xy 按位

x ^ y

xy 按位 异或

x & y

xy 按位

x << n

x 左移 n

(1)(2)

x >> n

x 右移 n

(1)(3)

~x

x 逐位取反

注释:

  1. 负的移位数是非法的,会导致引发 ValueError

  2. A left shift by n bits is equivalent to multiplication by pow(2, n). A long integer is returned if the result exceeds the range of plain integers.

  3. A right shift by n bits is equivalent to division by pow(2, n).

5.4.2. 整数类型的附加方法

The integer types implement the numbers.Integral abstract base class. In addition, they provide one more method:

int.bit_length()
long.bit_length()

返回以二进制表示一个整数所需要的位数,不包括符号位和前面的零:

>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6

更准确地说,如果 x 非零,则 x.bit_length() 是使得 2**(k-1) <= abs(x) < 2**k 的唯一正整数 k。 同样地,当 abs(x) 小到足以具有正确的舍入对数时,则 k = 1 + int(log(abs(x), 2))。 如果 x 为零,则 x.bit_length() 返回 0

等价于:

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6

2.7 新版功能.

5.4.3. 浮点类型的附加方法

float 类型实现了 numbers.Real abstract base class。 float 还具有以下附加方法。

float.as_integer_ratio()

返回一对整数,其比率正好等于原浮点数并且分母为正数。 无穷大会引发 OverflowError 而 NaN 则会引发 ValueError

2.6 新版功能.

float.is_integer()

如果 float 实例可用有限位整数表示则返回 True,否则返回 False:

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

2.6 新版功能.

两个方法均支持与十六进制数字符串之间的转换。 由于 Python 浮点数在内部存储为二进制数,因此浮点数与 十进制数 字符串之间的转换往往会导致微小的舍入错误。 而十六进制数字符串却允许精确地表示和描述浮点数。 这在进行调试和数值工作时非常有用。

float.hex()

以十六进制字符串的形式返回一个浮点数表示。 对于有限浮点数,这种表示法将总是包含前导的 0x 和尾随的 p 加指数。

2.6 新版功能.

float.fromhex(s)

返回以十六进制字符串 s 表示的浮点数的类方法。 字符串 s 可以带有前导和尾随的空格。

2.6 新版功能.

请注意 float.hex() 是实例方法,而 float.fromhex() 是类方法。

十六进制字符串采用的形式为:

[sign] ['0x'] integer ['.' fraction] ['p' exponent]

可选的 sign 可以是 +-integerfraction 是十六进制数码组成的字符串,exponent 是带有可选前导符的十进制整数。 大小写没有影响,在 integer 或 fraction 中必须至少有一个十六进制数码。 此语法类似于 C99 标准的 6.4.4.2 小节中所描述的语法,也是 Java 1.5 以上所使用的语法。 特别地,float.hex() 的输出可以用作 C 或 Java 代码中的十六进制浮点数字面值,而由 C 的 %a 格式字符或 Java 的 Double.toHexString 所生成的十六进制数字符串由为 float.fromhex() 所接受。

请注意 exponent 是十进制数而非十六进制数,它给出要与系数相乘的 2 的幂次。 例如,十六进制数字符串 0x3.a7p10 表示浮点数 (3 + 10./16 + 7./16**2) * 2.0**103740.0:

>>> float.fromhex('0x3.a7p10')
3740.0

3740.0 应用反向转换会得到另一个代表相同数值的十六进制数字符串:

>>> float.hex(3740.0)
'0x1.d380000000000p+11'

5.5. 迭代器类型

2.2 新版功能.

Python 支持在容器中进行迭代的概念。 这是通过使用两个单独方法来实现的;它们被用于允许用户自定义类对迭代的支持。 将在下文中详细描述的序列总是支持迭代方法。

容器对象要提供迭代支持,必须定义一个方法:

container.__iter__()

返回一个迭代器对象。 该对象需要支持下文所述的迭代器协议。 如果容器支持不同的迭代类型,则可以提供额外的方法来专门地请求不同迭代类型的迭代器。 (支持多种迭代形式的对象的例子有同时支持广度优先和深度优先遍历的树结构。) 此方法对应于 Python/C API 中 Python 对象类型结构体的 tp_iter 槽位。

迭代器对象自身需要支持以下两个方法,它们共同组成了 迭代器协议:

iterator.__iter__()

返回迭代器对象本身。 这是同时允许容器和迭代器配合 forin 语句使用所必须的。 此方法对应于 Python/C API 中 Python 对象类型结构体的 tp_iter 槽位。

iterator.next()

从容器中返回下一项。 如果已经没有项可返回,则会引发 StopIteration 异常。 此方法对应于 Python/C API 中 Python 对象类型结构体的 tp_iternext 槽位。

Python 定义了几种迭代器对象以支持对一般和特定序列类型、字典和其他更特别的形式进行迭代。 除了迭代器协议的实现,特定类型的其他性质对迭代操作来说都不重要。

The intention of the protocol is that once an iterator’s next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken. (This constraint was added in Python 2.3; in Python 2.2, various iterators are broken according to this rule.)

5.5.1. 生成器类型

Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() methods. More information about generators can be found in the documentation for the yield expression.

5.6. Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange

There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.

For other containers see the built in dict and set classes, and the collections module.

String literals are written in single or double quotes: 'xyzzy', "frobozz". See String literals for more about string literals. Unicode strings are much like strings, but are specified in the syntax using a preceding 'u' character: u'abc', u"def". In addition to the functionality described here, there are also string-specific methods described in the 字符串的方法 section. Lists are constructed with square brackets, separating items with commas: [a, b, c]. Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,).

Bytearray objects are created with the built-in function bytearray().

Buffer objects are not directly supported by Python syntax, but can be created by calling the built-in function buffer(). They don’t support concatenation or repetition.

Objects of type xrange are similar to buffers in that there is no specific syntax to create them, but they are created using the xrange() function. They don’t support slicing, concatenation or repetition, and using in, not in, min() or max() on them is inefficient.

Most sequence types support the following operations. The in and not in operations have the same priorities as the comparison operations. The + and * operations have the same priority as the corresponding numeric operations. 3 Additional methods are provided for 可变序列类型.

This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type; n, i and j are integers:

运算

结果:

注释

x in s

如果 s 中的某项等于 x 则结果为 True,否则为 False

(1)

x not in s

如果 s 中的某项等于 x 则结果为 False,否则为 True

(1)

s + t

st 相拼接

(6)

s * n, n * s

相当于 s 与自身进行 n 次拼接

(2)

s[i]

s 的第 i 项,起始为 0

(3)

s[i:j]

sij 的切片

(3)(4)

s[i:j:k]

sij 步长为 k 的切片

(3)(5)

len(s)

s 的长度

min(s)

s 的最小项

max(s)

s 的最大项

s.index(x)

index of the first occurrence of x in s

s.count(x)

xs 中出现的总次数

Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see 比较运算 in the language reference.)

注释:

  1. When s is a string or Unicode string object the in and not in operations act like a substring test. In Python versions before 2.3, x had to be a string of length 1. In Python 2.3 and beyond, x may be a string of any length.

  2. Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

    >>> lists = [[]] * 3
    >>> lists
    [[], [], []]
    >>> lists[0].append(3)
    >>> lists
    [[3], [3], [3]]
    

    What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

    >>> lists = [[] for i in range(3)]
    >>> lists[0].append(3)
    >>> lists[1].append(5)
    >>> lists[2].append(7)
    >>> lists
    [[3], [5], [7]]
    

    进一步的解释可以在 FAQ 条目 如何创建多维列表? 中查看。

  3. 如果 ij 为负值,则索引顺序是相对于序列 s 的末尾: 索引号会被替换为 len(s) + ilen(s) + j。 但要注意 -0 仍然为 0

  4. sij 的切片被定义为所有满足 i <= k < j 的索引号 k 的项组成的序列。 如果 ij 大于 len(s),则使用 len(s)。 如果 i 被省略或为 None,则使用 0。 如果 j 被省略或为 None,则使用 len(s)。 如果 i 大于等于 j,则切片为空。

  5. sij 步长为 k 的切片被定义为所有满足 0 <= n < (j-i)/k 的索引号 x = i + n*k 的项组成的序列。 换句话说,索引号为 i, i+k, i+2*k, i+3*k,以此类推,当达到 j 时停止 (但一定不包括 j)。 当 k 为正值时,ij 会被减至不大于 len(s)。 当 k 为负值时,ij 会被减至不大于 len(s) - 1。 如果 ij 被省略或为 None,它们会成为“终止”值 (是哪一端的终止值则取决于 k 的符号)。 请注意,k 不可为零。 如果 kNone,则当作 1 处理。

  6. CPython implementation detail: If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s = s + t or s += t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

    在 2.4 版更改: Formerly, string concatenation never occurred in-place.

5.6.1. 字符串的方法

Below are listed the string methods which both 8-bit strings and Unicode objects support. Some of them are also available on bytearray objects.

In addition, Python’s strings support the sequence type methods described in the Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange section. To output formatted strings use template strings or the % operator described in the String Formatting Operations section. Also, see the re module for string functions based on regular expressions.

str.capitalize()

返回原字符串的副本,其首个字符大写,其余为小写。

For 8-bit strings, this method is locale-dependent.

str.center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified fillchar (default is a space).

在 2.4 版更改: Support for the fillchar argument.

str.count(sub[, start[, end]])

反回子字符串 sub 在 [start, end] 范围内非重叠出现的次数。 可选参数 startend 会被解读为切片表示法。

str.decode([encoding[, errors]])

Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section 编解码器基类.

2.2 新版功能.

在 2.3 版更改: Support for other error handling schemes added.

在 2.7 版更改: 加入了对关键字参数的支持。

str.encode([encoding[, errors]])

Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section 编解码器基类. For a list of possible encodings, see section 标准编码.

2.0 新版功能.

在 2.3 版更改: Support for 'xmlcharrefreplace' and 'backslashreplace' and other error handling schemes added.

在 2.7 版更改: 加入了对关键字参数的支持。

str.endswith(suffix[, start[, end]])

如果字符串以指定的 suffix 结束返回 True,否则返回 Falsesuffix 也可以为由多个供查找的后缀构成的元组。 如果有可选项 start,将从所指定位置开始检查。 如果有可选项 end,将在所指定位置停止比较。

在 2.5 版更改: Accept tuples as suffix.

str.expandtabs([tabsize])

返回字符串的副本,其中所有的制表符会由一个或多个空格替换,具体取决于当前列位置和给定的制表符宽度。 每 tabsize 个字符设为一个制表位(默认值 8 时设定的制表位在列 0, 8, 16 依次类推)。 要展开字符串,当前列将被设为零并逐一检查字符串中的每个字符。 如果字符为制表符 (\t),则会在结果中插入一个或多个空格符,直到当前列等于下一个制表位。 (制表符本身不会被复制。) 如果字符为换行符 (\n) 或回车符 (\r),它会被复制并将当前列重设为零。 任何其他字符会被不加修改地复制并将当前列加一,不论该字符在被打印时会如何显示。

>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
str.find(sub[, start[, end]])

返回子字符串 subs[start:end] 切片内被找到的最小索引。 可选参数 startend 会被解读为切片表示法。 如果 sub 未被找到则返回 -1

注解

find() 方法应该只在你需要知道 sub 所在位置时使用。 要检查 sub 是否为子字符串,请使用 in 操作符:

>>> 'Py' in 'Python'
True
str.format(*args, **kwargs)

执行字符串格式化操作。 调用此方法的字符串可以包含字符串字面值或者以花括号 {} 括起来的替换域。 每个替换域可以包含一个位置参数的数字索引,或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替换为对应参数的字符串值。

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

请参阅 格式字符串语法 了解有关可以在格式字符串中指定的各种格式选项的说明。

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

2.6 新版功能.

str.index(sub[, start[, end]])

Like find(), but raise ValueError when the substring is not found.

str.isalnum()

Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.

str.isalpha()

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.

str.islower()

Return true if all cased characters 4 in the string are lowercase and there is at least one cased character, false otherwise.

For 8-bit strings, this method is locale-dependent.

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.

str.istitle()

Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.

For 8-bit strings, this method is locale-dependent.

str.isupper()

Return true if all cased characters 4 in the string are uppercase and there is at least one cased character, false otherwise.

For 8-bit strings, this method is locale-dependent.

str.join(iterable)

Return a string which is the concatenation of the strings in iterable. If there is any Unicode object in iterable, return a Unicode instead. A TypeError will be raised if there are any non-string or non Unicode object values in iterable. The separator between elements is the string providing this method.

str.ljust(width[, fillchar])

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than or equal to len(s).

在 2.4 版更改: Support for the fillchar argument.

str.lower()

返回原字符串的副本,其所有区分大小写的字符 4 均转换为小写。

For 8-bit strings, this method is locale-dependent.

str.lstrip([chars])

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

在 2.2.2 版更改: Support for the chars argument.

str.partition(sep)

sep 首次出现的位置拆分字符串,返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身,以及分隔符之后的部分。 如果分隔符未找到,则返回的 3 元组中包含字符本身以及两个空字符串。

2.5 新版功能.

str.replace(old, new[, count])

返回字符串的副本,其中出现的所有子字符串 old 都将被替换为 new。 如果给出了可选参数 count,则只替换前 count 次出现。

str.rfind(sub[, start[, end]])

返回子字符串 sub 在字符串内被找到的最大(最右)索引,这样 sub 将包含在 s[start:end] 当中。 可选参数 startend 会被解读为切片表示法。 如果未找到则返回 -1

str.rindex(sub[, start[, end]])

类似于 rfind(),但在子字符串 sub 未找到时会引发 ValueError

str.rjust(width[, fillchar])

Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than or equal to len(s).

在 2.4 版更改: Support for the fillchar argument.

str.rpartition(sep)

sep 最后一次出现的位置拆分字符串,返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身,以及分隔符之后的部分。 如果分隔符未找到,则返回的 3 元组中包含两个空字符串以及字符串本身。

2.5 新版功能.

str.rsplit([sep[, maxsplit]])

返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。 如果给出了 maxsplit,则最多进行 maxsplit 次拆分,从 最右边 开始。 如果 sep 未指定或为 None,任何空白字符串都会被作为分隔符。 除了从右边开始拆分,rsplit() 的其他行为都类似于下文所述的 split()

2.4 新版功能.

str.rstrip([chars])

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

在 2.2.2 版更改: Support for the chars argument.

str.split([sep[, maxsplit]])

返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。 如果给出了 maxsplit,则最多进行 maxsplit 次拆分(因此,列表最多会有 maxsplit+1 个元素)。 如果 maxsplit 未指定或为 -1,则不限制拆分次数(进行所有可能的拆分)。

如果给出了 sep,则连续的分隔符不会被组合在一起而是被视为分隔空字符串 (例如 '1,,2'.split(',') 将返回 ['1', '', '2'])。 sep 参数可能由多个字符组成 (例如 '1<>2<>3'.split('<>') 将返回 ['1', '2', '3'])。 使用指定的分隔符拆分空字符串将返回 ['']

如果 sep 未指定或为 None,则会应用另一种拆分算法:连续的空格会被视为单个分隔符,其结果将不包含开头或末尾的空字符串,如果字符串包含前缀或后缀空格的话。 因此,使用 None 拆分空字符串或仅包含空格的字符串将返回 []

For example, ' 1  2   3  '.split() returns ['1', '2', '3'], and '  1  2   3  '.split(None, 1) returns ['1', '2   3  '].

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.

Python recognizes "\r", "\n", and "\r\n" as line boundaries for 8-bit strings.

例如

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

不同于 split(),当给出了分隔字符串 sep 时,对于空字符串此方法将返回一个空列表,而末尾的换行不会令结果中增加额外的行:

>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

作为比较,split('\n') 的结果为:

>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']
unicode.splitlines([keepends])

Return a list of the lines in the string, like str.splitlines(). However, the Unicode method splits on the following line boundaries, which are a superset of the universal newlines recognized for 8-bit strings.

表示符

描述

\n

换行

\r

回车

\r\n

回车 + 换行

\v\x0b

行制表符

\f\x0c

换表单

\x1c

文件分隔符

\x1d

组分隔符

\x1e

记录分隔符

\x85

下一行 (C1 控制码)

\u2028

行分隔符

\u2029

段分隔符

在 2.7 版更改: \v\f 被添加到行边界列表

str.startswith(prefix[, start[, end]])

如果字符串以指定的 prefix 开始则返回 True,否则返回 Falseprefix 也可以为由多个供查找的前缀构成的元组。 如果有可选项 start,将从所指定位置开始检查。 如果有可选项 end,将在所指定位置停止比较。

在 2.5 版更改: Accept tuples as prefix.

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'

在 2.2.2 版更改: Support for the chars argument.

str.swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa.

For 8-bit strings, this method is locale-dependent.

str.title()

返回原字符串的标题版本,其中每个单词第一个字母为大写,其余字母为小写。

该算法使用一种简单的与语言无关的定义,将连续的字母组合视为单词。 该定义在多数情况下都很有效,但它也意味着代表缩写形式与所有格的撇号也会成为单词边界,这可能导致不希望的结果:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

可以使用正则表达式来构建针对撇号的特别处理:

>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."

For 8-bit strings, this method is locale-dependent.

str.translate(table[, deletechars])

Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.

You can use the maketrans() helper function in the string module to create a translation table. For string objects, set the table argument to None for translations that only delete characters:

>>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt'

2.6 新版功能: Support for a None table argument.

For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted. Note, a more flexible approach is to create a custom character mapping codec using the codecs module (see encodings.cp1251 for an example).

str.upper()

返回原字符串的副本,其中所有区分大小写的字符 4 均转换为大写。 请注意如果 s 包含不区分大小写的字符或者如果结果字符的 Unicode 类别不是 “Lu” (Letter, uppercase) 而是 “Lt” (Letter, titlecase) 则 s.upper().isupper() 有可能为 False

For 8-bit strings, this method is locale-dependent.

str.zfill(width)

Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than or equal to len(s).

2.2.2 新版功能.

The following methods are present only on unicode objects:

unicode.isnumeric()

Return True if there are only numeric characters in S, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH.

unicode.isdecimal()

Return True if there are only decimal characters in S, False otherwise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.

5.6.2. String Formatting Operations

String and Unicode objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.

如果 format 要求一个单独参数,则 values 可以为一个非元组对象。 5 否则的话,values 必须或者是一个包含项数与格式字符串中指定的转换符项数相同的元组,或者是一个单独映射对象(例如字典)。

转换标记符包含两个或更多字符并具有以下组成,且必须遵循此处规定的顺序:

  1. '%' 字符,用于标记转换符的起始。

  2. 映射键(可选),由加圆括号的字符序列组成 (例如 (somename))。

  3. 转换旗标(可选),用于影响某些转换类型的结果。

  4. 最小字段宽度(可选)。 如果指定为 '*' (星号),则实际宽度会从 values 元组的下一元素中读取,要转换的对象则为最小字段宽度和可选的精度之后的元素。

  5. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.

  6. 长度修饰符(可选)。

  7. 转换类型。

当右边的参数为一个字典(或其他映射类型)时,字符串中的格式 必须 包含加圆括号的映射键,对应 '%' 字符之后字典中的每一项。 映射键将从映射中选取要格式化的值。 例如:

>>> print '%(language)s has %(number)03d quote types.' % \
...       {"language": "Python", "number": 2}
Python has 002 quote types.

在此情况下格式中不能出现 * 标记符(因其需要一个序列类的参数列表)。

转换旗标为:

标志

含义

'#'

值的转换将使用“替代形式”(具体定义见下文)。

'0'

转换将为数字值填充零字符。

'-'

转换值将靠左对齐(如果同时给出 '0' 转换,则会覆盖后者)。

' '

(空格) 符号位转换产生的正数(或空字符串)前将留出一个空格。

'+'

符号字符 ('+''-') 将显示于转换结果的开头(会覆盖 “空格” 旗标)。

可以给出长度修饰符 (h, lL),但会被忽略,因为对 Python 来说没有必要 – 所以 %ld 等价于 %d

转换类型为:

转换符

含义

注释

'd'

有符号十进制整数。

'i'

有符号十进制整数。

'o'

有符号八进制数。

(1)

'u'

过时类型 – 等价于 'd'

(7)

'x'

有符号十六进制数(小写)。

(2)

'X'

有符号十六进制数(大写)。

(2)

'e'

浮点指数格式(小写)。

(3)

'E'

浮点指数格式(大写)。

(3)

'f'

浮点十进制格式。

(3)

'F'

浮点十进制格式。

(3)

'g'

浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格式,否则使用十进制格式。

(4)

'G'

浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格式,否则使用十进制格式。

(4)

'c'

单个字符(接受整数或单个字符的字符串)。

'r'

String (converts any Python object using repr()).

(5)

's'

字符串(使用 str() 转换任何 Python 对象)。

(6)

'%'

不转换参数,在结果中输出一个 '%' 字符。

注释:

  1. The alternate form causes a leading zero ('0') to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

  2. 此替代形式会在第一个数码之前插入 '0x''0X' 前缀(取决于是使用 'x' 还是 'X' 格式)。

  3. 此替代形式总是会在结果中包含一个小数点,即使其后并没有数码。

    小数点后的数码位数由精度决定,默认为 6。

  4. 此替代形式总是会在结果中包含一个小数点,末尾各位的零不会如其他情况下那样被移除。

    小数点前后的有效数码位数由精度决定,默认为 6。

  5. The %r conversion was added in Python 2.0.

    The precision determines the maximal number of characters used.

  6. If the object or format provided is a unicode string, the resulting string will also be unicode.

    The precision determines the maximal number of characters used.

  7. 参见 PEP 237

由于 Python 字符串显式指明长度,%s 转换不会将 '\0' 视为字符串的结束。

在 2.7 版更改: 绝对值超过 1e50 的 %f 转换不会再被替换为 %g 转换。

Additional string operations are defined in standard modules string and re.

5.6.3. XRange Type

The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages.

XRange objects have very little behavior: they only support indexing, iteration, and the len() function.

5.6.4. 可变序列类型

List and bytearray objects support additional operations that allow in-place modification of the object. Other mutable sequence types (when added to the language) should also support these operations. Strings and tuples are immutable sequence types: such objects cannot be modified once created. The following operations are defined on mutable sequence types (where x is an arbitrary object):

运算

结果:

注释

s[i] = x

s 的第 i 项替换为 x

s[i:j] = t

sij 的切片替换为可迭代对象 t 的内容

del s[i:j]

等同于 s[i:j] = []

s[i:j:k] = t

s[i:j:k] 的元素替换为 t 的元素

(1)

del s[i:j:k]

从列表中移除 s[i:j:k] 的元素

s.append(x)

same as s[len(s):len(s)] = [x]

(2)

s.extend(t)s += t

for the most part the same as s[len(s):len(s)] = t

(3)

s *= n

使用 s 的内容重复 n 次来对其进行更新

(11)

s.count(x)

return number of i’s for which s[i] == x

s.index(x[, i[, j]])

return smallest k such that s[k] == x and i <= k < j

(4)

s.insert(i, x)

same as s[i:i] = [x]

(5)

s.pop([i])

same as x = s[i]; del s[i]; return x

(6)

s.remove(x)

same as del s[s.index(x)]

(4)

s.reverse()

就地将列表中的元素逆序。

(7)

s.sort([cmp[, key[, reverse]]])

sort the items of s in place

(7)(8)(9)(10)

注释:

  1. t must have the same length as the slice it is replacing.

  2. The C implementation of Python has historically accepted multiple parameters and implicitly joined them into a tuple; this no longer works in Python 2.0. Use of this misfeature has been deprecated since Python 1.4.

  3. t can be any iterable object.

  4. Raises ValueError when x is not found in s. When a negative index is passed as the second or third parameter to the index() method, the list length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices.

    在 2.3 版更改: Previously, index() didn’t have arguments for specifying start and stop positions.

  5. When a negative index is passed as the first parameter to the insert() method, the list length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices.

    在 2.3 版更改: Previously, all negative indices were truncated to zero.

  6. The pop() method’s optional argument i defaults to -1, so that by default the last item is removed and returned.

  7. The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

  8. The sort() method takes optional arguments for controlling the comparisons.

    cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

    key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

    reverse 为一个布尔值。 如果设为 True,则每个列表元素将按反向顺序比较进行排序。

    In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

    在 2.3 版更改: Support for None as an equivalent to omitting cmp was added.

    在 2.4 版更改: Support for key and reverse was added.

  9. Starting with Python 2.3, the sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

  10. CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python 2.3 and newer makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.

  11. The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange.

5.7. 集合类型 — set, frozenset

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built in dict, list, and tuple classes, and the collections module.)

2.4 新版功能.

与其他多项集一样,集合也支持 x in set, len(set)for x in set。 作为一种无序的多项集,集合并不记录元素位置或插入顺序。 相应地,集合不支持索引、切片或其他序列类的操作。

目前有两种内置集合类型,setfrozensetset 类型是可变的 — 其内容可以使用 add()remove() 这样的方法来改变。 由于是可变类型,它没有哈希值,且不能被用作字典的键或其他集合的元素。 frozenset 类型是不可变并且为 hashable — 其内容在被创建后不能再改变;因此它可以被用作字典的键或其他集合的元素。

As of Python 2.7, non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor.

两个类的构造器具有相同的作用方式:

class set([iterable])
class frozenset([iterable])

返回一个新的 set 或 frozenset 对象,其元素来自于 iterable。 集合的元素必须为 hashable。 要表示由集合对象构成的集合,所有的内层集合必须为 frozenset 对象。 如果未指定 iterable,则将返回一个新的空集合。

setfrozenset 的实例提供以下操作:

len(s)

返回集合 s 中的元素数量(即 s 的基数)。

x in s

检测 x 是否为 s 中的成员。

x not in s

检测 x 是否非 s 中的成员。

isdisjoint(other)

如果集合中没有与 other 共有的元素则返回 True。 当且仅当两个集合的交集为空集合时,两者为不相交集合。

2.6 新版功能.

issubset(other)
set <= other

检测是否集合中的每个元素都在 other 之中。

set < other

检测集合是否为 other 的真子集,即 set <= other and set != other

issuperset(other)
set >= other

检测是否 other 中的每个元素都在集合之中。

set > other

检测集合是否为 other 的真超集,即 set >= other and set != other

union(*others)
set | other | ...

返回一个新集合,其中包含来自原集合以及 others 指定的所有集合中的元素。

在 2.6 版更改: Accepts multiple input iterables.

intersection(*others)
set & other & ...

返回一个新集合,其中包含原集合以及 others 指定的所有集合中共有的元素。

在 2.6 版更改: Accepts multiple input iterables.

difference(*others)
set - other - ...

返回一个新集合,其中包含原集合中在 others 指定的其他集合中不存在的元素。

在 2.6 版更改: Accepts multiple input iterables.

symmetric_difference(other)
set ^ other

返回一个新集合,其中的元素或属于原集合或属于 other 指定的其他集合,但不能同时属于两者。

copy()

返回原集合的浅拷贝。

请注意,非运算符版本的 union(), intersection(), difference(),以及 symmetric_difference(), issubset()issuperset() 方法会接受任意可迭代对象作为参数。 相比之下,它们所对应的运算符版本则要求其参数为集合。 这就排除了容易出错的构造形式例如 set('abc') & 'cbs',而推荐可读性更强的 set('abc').intersection('cbs')

setfrozenset 均支持集合与集合的比较。 两个集合当且仅当每个集合中的每个元素均包含于另一个集合之内(即各为对方的子集)时则相等。 一个集合当且仅当其为另一个集合的真子集(即为后者的子集但两者不相等)时则小于另一个集合。 一个集合当且仅当其为另一个集合的真超集(即为后者的超集但两者不相等)时则大于另一个集合。

set 的实例与 frozenset 的实例之间基于它们的成员进行比较。 例如 set('abc') == frozenset('abc') 返回 Trueset('abc') in set([frozenset('abc')]) 也一样。

The subset and equality comparisons do not generalize to a total ordering function. For example, any two non-empty disjoint sets are not equal and are not subsets of each other, so all of the following return False: a<b, a==b, or a>b. Accordingly, sets do not implement the __cmp__() method.

由于集合仅定义了部分排序(子集关系),因此由集合构成的列表 list.sort() 方法的输出并无定义。

集合的元素,与字典的键类似,必须为 hashable

混合了 set 实例与 frozenset 的二进制位运算将返回与第一个操作数相同的类型。例如: frozenset('ab') | set('bc') 将返回 frozenset 的实例。

下表列出了可用于 set 而不能用于不可变的 frozenset 实例的操作:

update(*others)
set |= other | ...

更新集合,添加来自 others 中的所有元素。

在 2.6 版更改: Accepts multiple input iterables.

intersection_update(*others)
set &= other & ...

更新集合,只保留其中在所有 others 中也存在的元素。

在 2.6 版更改: Accepts multiple input iterables.

difference_update(*others)
set -= other | ...

更新集合,移除其中也存在于 others 中的元素。

在 2.6 版更改: Accepts multiple input iterables.

symmetric_difference_update(other)
set ^= other

更新集合,只保留存在于集合的一方而非共同存在的元素。

add(elem)

将元素 elem 添加到集合中。

remove(elem)

从集合中移除元素 elem。 如果 elem 不存在于集合中则会引发 KeyError

discard(elem)

如果元素 elem 存在于集合中则将其移除。

pop()

从集合中移除并返回任意一个元素。 如果集合为空则会引发 KeyError

clear()

从集合中移除所有元素。

请注意,非运算符版本的 update(), intersection_update(), difference_update()symmetric_difference_update() 方法将接受任意可迭代对象作为参数。

请注意,__contains__(), remove()discard() 方法的 elem 参数可能是一个 set。 为支持对一个等价的 frozenset 进行搜索,会根据 elem 临时创建一个该类型对象。

参见

Comparison to the built-in set types

Differences between the sets module and the built-in set types.

5.8. 映射类型 — dict

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. (For other containers see the built in list, set, and tuple classes, and the collections module.)

字典的键 几乎 可以是任何值。 非 hashable 的值,即包含列表、字典或其他可变类型的值(此类对象基于值而非对象标识进行比较)不可用作键。 数字类型用作键时遵循数字比较的一般规则:如果两个数值相等 (例如 11.0) 则两者可以被用来索引同一字典条目。 (但是请注意,由于计算机对于浮点数存储的只是近似值,因此将其用作字典键是不明智的。)

字典可以通过将以逗号分隔的 键: 对列表包含于花括号之内来创建,例如: {'jack': 4098, 'sjoerd': 4127}{4098: 'jack', 4127: 'sjoerd'},也可以通过 dict 构造器来创建。

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

返回一个新的字典,基于可选的位置参数和可能为空的关键字参数集来初始化。

如果没有给出位置参数,将创建一个空字典。 如果给出一个位置参数并且其属于映射对象,将创建一个具有与映射对象相同键值对的字典。 否则的话,位置参数必须为一个 iterable 对象。 该可迭代对象中的每一项本身必须为一个刚好包含两个元素的可迭代对象。 每一项中的第一个对象将成为新字典的一个键,第二个对象将成为其对应的值。 如果一个键出现一次以上,该键的最后一个值将成为其在新字典中对应的值。

如果给出了关键字参数,则关键字参数及其值会被加入到基于位置参数创建的字典。 如果要加入的键已存在,来自关键字参数的值将替代来自位置参数的值。

作为演示,以下示例返回的字典均等于 {"one": 1, "two": 2, "three": 3}:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

像第一个例子那样提供关键字参数的方式只能使用有效的 Python 标识符作为键。 其他方式则可使用任何有效的键。

2.2 新版功能.

在 2.3 版更改: Support for building a dictionary from keyword arguments added.

这些是字典所支持的操作(因而自定义的映射类型也应当支持):

len(d)

返回字典 d 中的项数。

d[key]

返回 d 中以 key 为键的项。 如果映射中不存在 key 则会引发 KeyError

如果字典的子类定义了方法 __missing__() 并且 key 不存在,则 d[key] 操作将调用该方法并附带键 key 作为参数。 d[key] 随后将返回或引发 __missing__(key) 调用所返回或引发的任何对象或异常。 没有其他操作或方法会发起调用 __missing__()。 如果未定义 __missing__(),则会引发 KeyError__missing__() 必须是一个方法;它不能是一个实例变量:

>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1

上面的例子显示了 collections.Counter 实现的部分代码。 还有另一个不同的 __missing__ 方法是由 collections.defaultdict 所使用的。

2.5 新版功能: Recognition of __missing__ methods of dict subclasses.

d[key] = value

d[key] 设为 value

del d[key]

d[key]d 中移除。 如果映射中不存在 key 则会引发 KeyError

key in d

如果 d 中存在键 key 则返回 True,否则返回 False

2.2 新版功能.

key not in d

等价于 not key in d

2.2 新版功能.

iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys().

clear()

移除字典中的所有元素。

copy()

返回原字典的浅拷贝。

fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None.

2.3 新版功能.

get(key[, default])

如果 key 存在于字典中则返回 key 的值,否则返回 default。 如果 default 未给出则默认为 None,因而此方法绝不会引发 KeyError

has_key(key)

Test for the presence of key in the dictionary. has_key() is deprecated in favor of key in d.

items()

Return a copy of the dictionary’s list of (key, value) pairs.

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

iteritems()

Return an iterator over the dictionary’s (key, value) pairs. See the note for dict.items().

Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

2.2 新版功能.

iterkeys()

Return an iterator over the dictionary’s keys. See the note for dict.items().

Using iterkeys() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

2.2 新版功能.

itervalues()

Return an iterator over the dictionary’s values. See the note for dict.items().

Using itervalues() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

2.2 新版功能.

keys()

Return a copy of the dictionary’s list of keys. See the note for dict.items().

pop(key[, default])

如果 key 存在于字典中则将其移除并返回其值,否则返回 default。 如果 default 未给出且 key 不存在于字典中,则会引发 KeyError

2.3 新版功能.

popitem()

Remove and return an arbitrary (key, value) pair from the dictionary.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

setdefault(key[, default])

如果字典存在键 key ,返回它的值。如果不存在,插入值为 default 的键 key ,并返回 defaultdefault 默认为 None

update([other])

使用来自 other 的键/值对更新字典,覆盖原有的键。 返回 None

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

在 2.4 版更改: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.

values()

Return a copy of the dictionary’s list of values. See the note for dict.items().

viewitems()

Return a new view of the dictionary’s items ((key, value) pairs). See below for documentation of view objects.

2.7 新版功能.

viewkeys()

Return a new view of the dictionary’s keys. See below for documentation of view objects.

2.7 新版功能.

viewvalues()

Return a new view of the dictionary’s values. See below for documentation of view objects.

2.7 新版功能.

Dictionaries compare equal if and only if they have the same (key, value) pairs.

5.8.1. 字典视图对象

The objects returned by dict.viewkeys(), dict.viewvalues() and dict.viewitems() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

字典视图可以被迭代以产生与其对应的数据,并支持成员检测:

len(dictview)

返回字典中的条目数。

iter(dictview)

返回字典中的键、值或项(以 (键, 值) 为元素的元组表示)的迭代器。

Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()].

在添加或删除字典中的条目期间对视图进行迭代可能引发 RuntimeError 或者无法完全迭代所有条目。

x in dictview

如果 x 是对应字典中存在的键、值或项(在最后一种情况下 x 应为一个 (键, 值) 元组) 则返回 True

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) Then these set operations are available (“other” refers either to another view or a set):

dictview & other

Return the intersection of the dictview and the other object as a new set.

dictview | other

Return the union of the dictview and the other object as a new set.

dictview - other

Return the difference between the dictview and the other object (all elements in dictview that aren’t in other) as a new set.

dictview ^ other

Return the symmetric difference (all elements either in dictview or other, but not in both) of the dictview and the other object as a new set.

一个使用字典视图的示例:

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.viewkeys()
>>> values = dishes.viewvalues()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order
>>> list(keys)
['eggs', 'bacon', 'sausage', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam', 'bacon']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}

5.9. File Objects

File objects are implemented using C’s stdio package and can be created with the built-in open() function. File objects are also returned by some other built-in functions and methods, such as os.popen() and os.fdopen() and the makefile() method of socket objects. Temporary files can be created using the tempfile module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.

When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.

Files have the following methods:

file.close()

Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.

As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically close f when the with block is exited:

from __future__ import with_statement # This isn't required in Python 2.6

with open("hello.txt") as f:
    for line in f:
        print line,

In older versions of Python, you would have needed to do this to get the same effect:

f = open("hello.txt")
try:
    for line in f:
        print line,
finally:
    f.close()

注解

Not all “file-like” types in Python support use as a context manager for the with statement. If your code is intended to work with any file-like object, you can use the function contextlib.closing() instead of using the object directly.

file.flush()

Flush the internal buffer, like stdio’s fflush(). This may be a no-op on some file-like objects.

注解

flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.

file.fileno()

Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the fcntl module or os.read() and friends.

注解

File-like objects which do not have a real file descriptor should not provide this method!

file.isatty()

Return True if the file is connected to a tty(-like) device, else False.

注解

If a file-like object is not associated with a real file, this method should not be implemented.

file.next()

A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer.

2.3 新版功能.

file.read([size])

Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.

注解

This function is simply a wrapper for the underlying fread() C function, and will behave the same in corner cases, such as whether the EOF value is cached.

file.readline([size])

Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). 6 If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately.

注解

Unlike stdio’s fgets(), the returned string contains null characters ('\0') if they occurred in the input.

file.readlines([sizehint])

Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.

file.xreadlines()

This method returns the same thing as iter(f).

2.1 新版功能.

2.3 版后已移除: Use for line in file instead.

file.seek(offset[, whence])

Set the file’s current position, like stdio’s fseek(). The whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file’s end). There is no return value.

For example, f.seek(2, os.SEEK_CUR) advances the position by two and f.seek(-3, os.SEEK_END) sets the position to the third to last.

Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). If the file is opened in text mode (without 'b'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

Note that not all file objects are seekable.

在 2.6 版更改: Passing float values as offset has been deprecated.

file.tell()

Return the file’s current position, like stdio’s ftell().

注解

On Windows, tell() can return illegal values (after an fgets()) when reading files with Unix-style line-endings. Use binary mode ('rb') to circumvent this problem.

file.truncate([size])

Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.

file.write(str)

Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

file.writelines(sequence)

Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines() does not add line separators.)

Files support the iterator protocol. Each iteration returns the same result as readline(), and iteration ends when the readline() method returns an empty string.

File objects also offer a number of other interesting attributes. These are not required for file-like objects, but should be implemented if they make sense for the particular object.

file.closed

bool indicating the current state of the file object. This is a read-only attribute; the close() method changes the value. It may not be available on all file-like objects.

file.encoding

The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be None, in which case the file uses the system default encoding for converting Unicode strings.

2.3 新版功能.

file.errors

The Unicode error handler used along with the encoding.

2.6 新版功能.

file.mode

The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter. This is a read-only attribute and may not be present on all file-like objects.

file.name

If the file object was created using open(), the name of the file. Otherwise, some string that indicates the source of the file object, of the form <...>. This is a read-only attribute and may not be present on all file-like objects.

file.newlines

If Python was built with universal newlines enabled (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file. The values it can take are '\r', '\n', '\r\n', None (unknown, no newlines read yet) or a tuple containing all the newline types seen, to indicate that multiple newline conventions were encountered. For files not opened in universal newlines read mode the value of this attribute will be None.

file.softspace

Boolean that indicates whether a space character needs to be printed before another value when using the print statement. Classes that are trying to simulate a file object should also have a writable softspace attribute, which should be initialized to zero. This will be automatic for most classes implemented in Python (care may be needed for objects that override attribute access); types implemented in C will have to provide a writable softspace attribute.

注解

This attribute is not used to control the print statement, but to allow the implementation of print to keep track of its internal state.

5.10. memoryview type

2.7 新版功能.

memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying. Memory is generally interpreted as simple bytes.

class memoryview(obj)

Create a memoryview that references obj. obj must support the buffer protocol. Built-in objects that support the buffer protocol include str and bytearray (but not unicode).

A memoryview has the notion of an element, which is the atomic memory unit handled by the originating object obj. For many simple types such as str and bytearray, an element is a single byte, but other third-party types may expose larger elements.

len(view) returns the total number of elements in the memoryview, view. The itemsize attribute will give you the number of bytes in a single element.

A memoryview supports slicing to expose its data. Taking a single index will return a single element as a str object. Full slicing will result in a subview:

>>> v = memoryview('abcefg')
>>> v[1]
'b'
>>> v[-1]
'g'
>>> v[1:4]
<memory at 0x77ab28>
>>> v[1:4].tobytes()
'bce'

If the object the memoryview is over supports changing its data, the memoryview supports slice assignment:

>>> data = bytearray('abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = 'z'
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = '123'
>>> data
bytearray(b'z123fg')
>>> v[2] = 'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot modify size of memoryview object

Notice how the size of the memoryview object cannot be changed.

memoryview has two methods:

tobytes()

Return the data in the buffer as a bytestring (an object of class str).

>>> m = memoryview("abc")
>>> m.tobytes()
'abc'
tolist()

Return the data in the buffer as a list of integers.

>>> memoryview("abc").tolist()
[97, 98, 99]

还存在一些可用的只读属性:

format

A string containing the format (in struct module style) for each element in the view. This defaults to 'B', a simple bytestring.

itemsize

The size in bytes of each element of the memoryview.

shape

一个整数元组,通过 ndim 的长度值给出内存所代表的 N 维数组的形状。

ndim

一个整数,表示内存所代表的多维数组具有多少个维度。

strides

一个整数元组,通过 ndim 的长度给出以字节表示的大小,以便访问数组中每个维度上的每个元素。

readonly

一个表明内存是否只读的布尔值。

5.11. 上下文管理器类型

2.5 新版功能.

Python’s with statement supports the concept of a runtime context defined by a context manager. This is implemented using two separate methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends.

The context management protocol consists of a pair of methods that need to be provided for a context manager object to define a runtime context:

contextmanager.__enter__()

Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the as clause of with statements using this context manager.

An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow open() to be used as the context expression in a with statement.

An example of a context manager that returns a related object is the one returned by decimal.localcontext(). These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the with statement without affecting code outside the with statement.

contextmanager.__exit__(exc_type, exc_val, exc_tb)

退出运行时上下文并返回一个布尔值旗标来表明所发生的任何异常是否应当被屏蔽。 如果在执行 with 语句的语句体期间发生了异常,则参数会包含异常的类型、值以及回溯信息。 在其他情况下三个参数均为 None

Returning a true value from this method will cause the with statement to suppress the exception and continue execution with the statement immediately following the with statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement.

The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code (such as contextlib.nested) to easily detect whether or not an __exit__() method has actually failed.

Python 定义了一些上下文管理器来支持简易的线程同步、文件或其他对象的快速关闭,以及更方便地操作活动的十进制算术上下文。 除了实现上下文管理协议以外,不同类型不会被特殊处理。 请参阅 contextlib 模块查看相关的示例。

Python’s generators and the contextlib.contextmanager decorator provide a convenient way to implement these protocols. If a generator function is decorated with the contextlib.contextmanager decorator, it will return a context manager implementing the necessary __enter__() and __exit__() methods, rather than the iterator produced by an undecorated generator function.

请注意,Python/C API 中 Python 对象的类型结构中并没有针对这些方法的专门槽位。 想要定义这些方法的扩展类型必须将它们作为普通的 Python 可访问方法来提供。 与设置运行时上下文的开销相比,单个类字典查找的开销可以忽略不计。

5.12. 其他内置类型

解释器支持一些其他种类的对象。 这些对象大都仅支持一两种操作。

5.12.1. 模块

模块唯一的特殊操作是属性访问: m.name,这里 m 为一个模块而 name 访问定义在 m 的符号表中的一个名称。 模块属性可以被赋值。 (请注意 import 语句严格来说也是对模块对象的一种操作;import foo 不要求存在一个名为 foo 的模块对象,而是要求存在一个对于名为 foo 的模块的 (永久性) 定义。)

每个模块都有一个特殊属性 __dict__。 这是包含模块的符号表的字典。 修改此字典将实际改变模块的符号表,但是无法直接对 __dict__ 赋值 (你可以写 m.__dict__['a'] = 1,这会将 m.a 定义为 1,但是你不能写 m.__dict__ = {})。 不建议直接修改 __dict__

内置于解释器中的模块会写成这样: <module 'sys' (built-in)>。 如果是从一个文件加载,则会写成 <module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>

5.12.2. 类与类实例

关于这些类型请参阅 对象、值与类型类定义

5.12.3. 函数

函数对象是通过函数定义创建的。 对函数对象的唯一操作是调用它: func(argument-list)

实际上存在两种不同的函数对象:内置函数和用户自定义函数。 两者支持同样的操作(调用函数),但实现方式不同,因此对象类型也不同。

更多信息请参阅 函数定义

5.12.4. 方法

方法是使用属性表示法来调用的函数。 存在两种形式:内置方法(例如列表的 append() 方法)和类实例方法。 内置方法由支持它们的类型来描述。

The implementation adds two special read-only attributes to class instance methods: m.im_self is the object on which the method operates, and m.im_func is the function implementing the method. Calling m(arg-1, arg-2, ..., arg-n) is completely equivalent to calling m.im_func(m.im_self, arg-1, arg-2, ..., arg-n).

Class instance methods are either bound or unbound, referring to whether the method was accessed through an instance or a class, respectively. When a method is unbound, its im_self attribute will be None and if called, an explicit self object must be passed as the first argument. In this case, self must be an instance of the unbound method’s class (or a subclass of that class), otherwise a TypeError is raised.

Like function objects, methods objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (meth.im_func), setting method attributes on either bound or unbound methods is disallowed. Attempting to set an attribute on a method results in an AttributeError being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:

>>> class C:
...     def method(self):
...         pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method'  # can't set on the method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'instancemethod' object has no attribute 'whoami'
>>> c.method.im_func.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'

更多信息请参阅 标准类型层级结构

5.12.5. 代码对象

Code objects are used by the implementation to represent “pseudo-compiled” executable Python code such as a function body. They differ from function objects because they don’t contain a reference to their global execution environment. Code objects are returned by the built-in compile() function and can be extracted from function objects through their func_code attribute. See also the code module.

A code object can be executed or evaluated by passing it (instead of a source string) to the exec statement or the built-in eval() function.

更多信息请参阅 标准类型层级结构

5.12.6. 类型对象

类型对象表示各种对象类型。 对象的类型可通过内置函数 type() 来获取。 类型没有特殊的操作。 标准库模块 types 定义了所有标准内置类型的名称。

Types are written like this: <type 'int'>.

5.12.7. 空对象

This object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name).

该对象的写法为 None

5.12.8. 省略符对象

This object is used by extended slice notation (see 切片). It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name).

It is written as Ellipsis. When in a subscript, it can also be written as ..., for example seq[...].

5.12.9. 未实现对象

This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See 比较运算 for more information.

该对象的写法为 NotImplemented

5.12.10. 布尔值

布尔值是两个常量对象 FalseTrue。 它们被用来表示逻辑上的真假(不过其他值也可被当作真值或假值)。 在数字类的上下文中(例如被用作算术运算符的参数时),它们的行为分别类似于整数 0 和 1。 内置函数 bool() 可被用来将任意值转换为布尔值,只要该值可被解析为一个逻辑值(参见之前的 逻辑值检测 部分)。

该对象的写法分别为 FalseTrue

5.12.11. 内部对象

有关此对象的信息请参阅 标准类型层级结构。 其中描述了栈帧对象、回溯对象以及切片对象等等。

5.13. 特殊属性

语言实现为部分对象类型添加了一些特殊的只读属性,它们具有各自的作用。 其中一些并不会被 dir() 内置函数所列出。

object.__dict__

一个字典或其他类型的映射对象,用于存储对象的(可写)属性。

object.__methods__

2.2 版后已移除: Use the built-in function dir() to get a list of an object’s attributes. This attribute is no longer available.

object.__members__

2.2 版后已移除: Use the built-in function dir() to get a list of an object’s attributes. This attribute is no longer available.

instance.__class__

类实例所属的类。

class.__bases__

由类对象的基类所组成的元组。

definition.__name__

The name of the class, type, function, method, descriptor, or generator instance.

The following attributes are only supported by new-style classes.

class.__mro__

此属性是由类组成的元组,在方法解析期间会基于它来查找基类。

class.mro()

此方法可被一个元类来重载,以为其实例定制方法解析顺序。 它会在类实例化时被调用,其结果存储于 __mro__ 之中。

class.__subclasses__()

Each new-style class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. Example:

>>> int.__subclasses__()
[<type 'bool'>]

备注

1

有关这些特殊方法的额外信息可参看 Python 参考指南 (基本定制)。

2

作为结果,列表 [1, 2][1.0, 2.0] 是相等的,元组的情况也类似。

3

它们必须如此,因为解析器无法区分这些操作数的类型。

4(1,2,3,4)

区分大小写的字符是指所属一般类别属性为 “Lu” (Letter, uppercase), “Ll” (Letter, lowercase) 或 “Lt” (Letter, titlecase) 之一的字符。

5

要格式化单独一个元组,那么你应当提供一个单例元组,其唯一的元素就是要被格式化的元组。

6

The advantage of leaving the newline on is that returning an empty string is then an unambiguous EOF indication. It is also possible (in cases where it might matter, for example, if you want to make an exact copy of a file while scanning its lines) to tell whether the last line of a file ended in a newline or not (yes this happens!).